在闭包中的未定义

时间:2016-03-20 20:45:45

标签: javascript loops closures



var createShoutOuts = function(numbers_list){
  var shoutOuts = [];
  for (var j = 0; j < numbers_list.length; j++) {
    shoutOuts.push(function() {
      var shout_out = 'This is shout out number ' + (j+1);
      console.log(shout_out + '. The number is ' + numbers_list[j]);
    });		
  }
  return shoutOuts;
};

var performShoutOuts = function(user_numbers){
  var readyForShout = createShoutOuts(user_numbers);
  for (var i = 0; i < readyForShout.length; i++) {
    readyForShout[i]();
  };
};

performShoutOuts([2,4,8]);
&#13;
&#13;
&#13;

我创建了以上内容来教自己封闭。输出总是:

  

&#39;这是4号号码。号码未定义&#39;

我理解它总是会说4号因为被推入shoutOuts数组的匿名函数引用了j变量,而不是j变量值的副本。因此,当readyForShout[i]();调用匿名函数时,for循环已经运行,并且我的值为4.

我不明白为什么说未定义?因为在我看来,传递给performShoutOuts的数组应该存储在闭包中,因此在readyForShout[i]();执行时应该可以访问。

我错过了什么?

1 个答案:

答案 0 :(得分:0)

尝试使用闭包真实:

var createShoutOuts = function(numbers_list){
  var shoutOuts = [];
  for (var j = 0; j < numbers_list.length; j++) {
    shoutOuts.push((function (j) {
      return function () {
        var shout_out = 'This is shout out number ' + (j+1);
        console.log(shout_out + '. The number is ' + numbers_list[j]);
      };
    })(j));
  }
  return shoutOuts;
};

var performShoutOuts = function(user_numbers){
  var readyForShout = createShoutOuts(user_numbers);
  for (var i = 0; i < readyForShout.length; i++) {
    readyForShout[i]();
  };
};

performShoutOuts([2,4,8]);