要求forloop不能按预期工作

时间:2018-05-27 20:25:00

标签: javascript arrays require

我有以下代码:

var tableRequiredList = [];

var requireListPath = [
    './slimShady.js',
    './chickaChicka.js'
];

var getRequires = function() {
  for (var i = 0; i < requireListPath.length; i++) {
    ((requireNamePath) => {
      try {
        console.log("INSIDE LOOP RESULT", i, require(requireNamePath)().getName()); // Outputs correct result for the index ("ChickaChicka")
        tableRequiredList.push({ "name": requireNamePath, "theReq": require(requireNamePath)() });
        // tableRequiredList.push({ "name": requireNamePath, "theReq": ((thePath) => { return require(thePath)(); })(requireNamePath) }); // This also doesn't seem to work.
      } catch(err) {
        console.log("Error importing: ", requireNamePath, "  Error reported: ", err);
      }
    })(requireListPath[i]);
  };
  console.log("NAME", tableRequiredList[0].name); // Outputs the correct result ("slimShady.js")
  console.log("FUNC NAME", tableRequiredList[0].theReq.getName()); // Always outputs the last item in requireListPath list ("ChickaChicka")
};

getRequires();

示例模块1 - slimShady.js

((module) => {
  module.exports = {};

  var exampleModuleName1 = function() {

    this.getName = function() {
      return 'myNameIsSlimShady';
    };

    return this;
  };

  module.exports = exampleModuleName1;
})(module);

示例模块2 - chickaChicka.js

((module) => {
  module.exports = {};

  var exampleModuleName2 = function() {

    this.getName = function() {
      return 'ChickaChicka';
    };

    return this;
  };

  module.exports = exampleModuleName2;
})(module);

为什么输出:

INSIDE LOOP RESULT 0 myNameIsSlimShady
INSIDE LOOP RESULT 1 ChickaChicka
NAME ./slimShady.js
FUNC NAME ChickaChicka

什么时候应该输出tableRequiredList数组的第一个索引?这似乎只发生在require()。我尝试过使用map和forEach,以及上面的闭包示例。所有结果都相同。

1 个答案:

答案 0 :(得分:0)

感谢@liliscent,我明白了。

只需将模块更改为:

((module) => {
  module.exports = {};

  var exampleModuleName2 = function() {
    var retr = {};

    retr.getName = function() {
      return 'ChickaChicka';
    };

    return retr;
  };

  module.exports = exampleModuleName2;
})(module);