Понимание примеров из «Понимания замыканий JavaScript с легкостью»

1

Последним примером http://javascriptissexy.com/understand-javascript-closures-with-ease/ является:

function celebrityIDCreator (theCelebrities) {
    var i;
    var uniqueID = 100;
    for (i = 0; i < theCelebrities.length; i++) {
        theCelebrities[i]["id"] = function (j)  { // the j parametric variable is the i passed in on invocation of this IIFE​
            return function () {
                return uniqueID + j; // each iteration of the for loop passes the current value of i into this IIFE and it saves the correct value to the array​
            } () // BY adding () at the end of this function, we are executing it immediately and returning just the value of uniqueID + j, instead of returning a function.​
        } (i); // immediately invoke the function passing the i variable as a parameter​
    }
    return theCelebrities;
};

​var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}];

​var createIdForActionCelebs = celebrityIDCreator (actionCelebs);

​var stalloneID = createIdForActionCelebs[0];

console.log(stalloneID.id); // 100​

console.log(createIdForActionCelebs[1].id); // 101

Я не понимаю, почему здесь требуется IIFE, я заменил celebrityIDCreator и дал те же результаты:

var celebrityIDCreator = function(theCelebrities) {
      var i;
      var uniqueID = 100;
      for (i = 0; i < theCelebrities.length; i++) {
          theCelebrities[i]["id"] = function (j) {
            return uniqueID + j;
              // return function () {

              // } () ;
          } (i);
      }

      return theCelebrities;
};

Может ли кто-нибудь объяснить это? Мне что-то не хватает?

Теги:
closures

1 ответ

1
Лучший ответ

Я думаю, что это ошибка в блоге. Если вы видите первый пример раздела Closures Gone Awry, id создается как функция. Но во втором примере, который вы имеете в виду и который направлен на решение ошибки в первом, id создается как свойство.

Я думаю, что второй пример должен быть таким, чтобы сделать его похожим на первое. Обратите внимание на примечания в коде, рядом с рассматриваемым IIFE и потреблением id как функции

function celebrityIDCreator(theCelebrities) {
  var i;
  var uniqueID = 100;
  for (i = 0; i < theCelebrities.length; i++) {
    theCelebrities[i]["id"] = function(j) { // the j parametric variable is the i passed in on invocation of this IIFE
      return function() {
        return uniqueID + j; // each iteration of the for loop passes the current value of i into this IIFE and it saves the correct value to the array
      } // NOTE. Not an IIFE
    }(i); // immediately invoke the function passing the i variable as a parameter
  }
  return theCelebrities;
};


var actionCelebs = [{
  name: "Stallone",
  id: 0
}, {
  name: "Cruise",
  id: 0
}, {
  name: "Willis",
  id: 0
}];


var createIdForActionCelebs = celebrityIDCreator(actionCelebs);


var stalloneID = createIdForActionCelebs[0];

console.log(stalloneID.id()); // 100 NOTE: Use as function

console.log(createIdForActionCelebs[1].id()); // 101 NOTE: Use as function

Кроме того, я считаю, что вы ничего не пропустили. Ваш код прав, если id должен быть свойством.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню