【问题标题】:Confused by closures in JavaScript [duplicate]对 JavaScript 中的闭包感到困惑 [重复]
【发布时间】:2011-12-31 14:23:19
【问题描述】:

可能重复:
How do JavaScript closures work?
Javascript closures and side effects in plain English? (separately)

我是 JavaScript 新手,但我对闭包的工作方式感到非常困惑。有人可以通俗地解释它们是什么或为什么有用吗?

【问题讨论】:

标签: javascript closures


【解决方案1】:

闭包在定义时类似于函数的上下文。每当定义函数时,都会存储上下文,即使函数的“正常”生命周期结束,如果您保留对函数执行过程中定义的元素的引用,它仍然可以访问上下文的元素(闭包),这实际上是您的函数在其定义中的范围。对不起我的英语不好,但可能这个例子会让你明白:

function test() {
  var a = "hello world";
  var checkValue = function() { alert(a); };
  checkValue();
  a = "hi again";
  return checkValue;
}

var pointerToCheckValue = test();  //it will print "hello world" and a closure will be created with the context where the checkValue function was defined.
pointerToCheckValue(); //it will execute the function checkValue with the context (closure) used when it was defined, so it still has access to the "a" variable

希望对你有帮助:-)

【讨论】:

    【解决方案2】:

    如果你从一个简单的使用开始,我从http://ejohn.org/apps/learn/#49得到的

    var num = 10; 
    
    function addNum(myNum){ 
      return num + myNum; 
    } 
    
    assert( addNum(5) == 15, "Add two numbers together, one from a closure." );
    

    发生的情况是变量num 被困(封闭)在addNum 函数中。

    如果你有这样的东西(预计不会正常运行),这会变得很方便:

    for(var t = 0; t < 5; t++) {
      var elem = document.getElementById('mydiv' + t);
      elem.onclick = function(e) {
         alert(t);
      };
    };
    

    这应该显示使用此事件处理程序设置的每个 div 的值 5。

    如果您将计数器的实例包含在事件处理程序中,那么每个实例可能会有所不同,这是预期的行为。

    这是一个相当高级的话题。一旦您对 javascript 更加熟悉了,您可能希望了解在那个时候学习它。

    【讨论】:

      【解决方案3】:

      我强烈推荐以下article。我发现这是理解闭包的一个很好的起点。

      【讨论】:

        猜你喜欢
        • 2013-10-21
        • 1970-01-01
        • 1970-01-01
        • 2017-02-28
        • 1970-01-01
        • 2015-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多