Требуется в forloop не работает, как ожидалось - PullRequest
0 голосов
/ 27 мая 2018

У меня есть следующий код:

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 ().Я попытался использовать карту и forEach, а также пример закрытия выше.Все имеют одинаковые результаты.

1 Ответ

0 голосов
/ 28 мая 2018

Благодаря @liliscent, я понял это.

Просто нужно поменять модули на это:

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

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

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

    return retr;
  };

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