JavaScript不支持带有局部变量的闭包吗? [英] Doesn't JavaScript support closures with local variables?

查看:67
本文介绍了JavaScript不支持带有局部变量的闭包吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此代码非常困惑:

  var closures = []; 
function create(){
for(var i = 0; i <5; i ++){
closureures [i] = function(){
alert + i);
};
}
}

function run(){
for(var i = 0; i <5; i ++){
closures [i] ();
}
}

create();
run();



从我的理解它应该打印0,1,2,3,4(不是这个



I尝试Rhino和Firefox。



有人可以向我解释这个行为吗?
提前Thx。

解决方案

通过添加一个额外的匿名函数修复Jon的回答:

  function create(){
for(var i = 0; i <5; i ++){
closureures [i] (function(tmp){
return function(){
alert(i =+ tmp);
};
}
}
}

解释是JavaScript的范围是函数级,不是块级的,并且创建闭包只是意味着封闭范围被添加到封闭函数的词法环境。



循环终止后,函数级变量 i 具有 5 的值,这是内部函数看到的。






注意:你应该注意不必要的函数对象创建,特别是在循环中;它的效率低,如果涉及DOM对象,很容易创建循环引用,因此在Internet Explorer中引入内存泄漏。


I am very puzzled about this code:

var closures = [];
function create() {
  for (var i = 0; i < 5; i++) {
    closures[i] = function() {
      alert("i = " + i);
    };
  }
}

function run() {
  for (var i = 0; i < 5; i++) {
    closures[i]();
  }
}

create();
run();

From my understanding it should print 0,1,2,3,4 (isn't this the concept of closures?).

Instead it prints 5,5,5,5,5.

I tried Rhino and Firefox.

Could someone explain this behavior to me? Thx in advance.

解决方案

Fixed Jon's answer by adding an additional anonymous function:

function create() {
  for (var i = 0; i < 5; i++) {
    closures[i] = (function(tmp) {
        return function() {
          alert("i = " + tmp);
        };
    })(i);
  }
}

The explanation is that JavaScript's scopes are function-level, not block-level, and creating a closure just means that the enclosing scope gets added to the lexical environment of the enclosed function.

After the loop terminates, the function-level variable i has the value 5, and that's what the inner function 'sees'.


As a side note: you should beware of unnecessary function object creation, espacially in loops; it's inefficient, and if DOM objects are involved, it's easy to create circular references and therefore introduce memory leaks in Internet Explorer.

这篇关于JavaScript不支持带有局部变量的闭包吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆