简体   繁体   English

通过一个小示例了解JavaScript闭包

[英]Understanding JavaScript Closures with a small example

I am trying to get around understanding javascript closures from a practical scenario.I know from a theoretical perspective , With the help of closures inner functions can have access to the variables in the enclosing function ie parent function. 我试图从实际情况中了解javascript闭包。从理论上讲,通过闭包,内部函数可以访问封闭函数(即父函数)中的变量。

I have read a couple of questions on stackOverflow as well. 我也阅读了关于stackOverflow的几个问题。

i am really missing the point of what is happening here? 我真的错过了这里发生的事情吗?

var foo = [];
for(var i=0;i<10;i++){
  foo[i] = function(){
  return i;
}  
}
console.log(foo[0]());

This gives me out a 10. Most of the articles say that by the time it reaches the inner anonymous function, The for loop is getting executed as a result the last value that is present in the loop which is 10 is being printed. 这给了我10。大多数文章说,当它到达内部匿名函数时,将执行for循环,结果将打印循环中存在的最后一个值10。

But i am still not able to get to the bottom of this. 但是我仍然无法深入了解这一点。

On Contrary, If i use something like: 相反,如果我使用类似的方法:

var foo = [];
for(var i=0;i<10;i++){
 (function(){
   var y =i;
   foo[i] = function(){
   return y;
 }
 })();
 }
console.log(foo[0]());

I am getting the output.Any help would be highly appreciated. 我正在得到输出。任何帮助将不胜感激。

In your first scenario, all of your functions added to the foo array are referencing the same var i . 在第一种情况下,添加到foo数组的所有函数都引用相同的var i All functions will return whatever i was set to last, which is 10 because during the last iteration of the loop that's what it's value was set to. 所有函数都将返回i设置为last的值,即10因为在循环的最后一次迭代期间将其值设置为该值。

In the second scenario, you are Immediately Invoking this function: 在第二种情况下,您将立即调用此功能:

(function(){
  var y =i;
  foo[i] = function(){
    return y;
  }
})();

By immediately invoking it you are effectively locking in the local state of var y , for each iteration of the loop - it provides a unique scope for each function added to the array. 通过立即调用它,您可以有效地将var y的本地状态锁定在循环的每次迭代中-它为添加到数组的每个函数提供了唯一的作用域。

maybe this code block helps 也许这个代码块有帮助

var foo = [];
for(var i = 0; i < 10; i++) {
    foo[i] = function() {
        return i; // is a reference and will always be the value, which 'i' have on function execution
    }
}
// 'i' is 10 here!
console.log(foo[0]()); // executing the function will return the current value of 'i'

///////////////////////////////////////

var foo = [];
for(var i=0;i<10;i++) {
    /* thats a IIFE (immediately invoked function expression) */
    (function(a) { // 'a' is now a local variable
        foo[a] = function() { // defines a function
            return a; // is a reference to local variable 'a'
        };
    })(i); // <- passing the current value of i as parameter to the invoked function
}
// 'i' is 10 here
console.log(foo[0]()); // returns the reference to 'a' within the same scope, where the function was defined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM