在JavaScript中被闭包困惑

use*_*031 28 javascript closures

可能重复:
JavaScript闭包如何工作?
Javascript闭包和简单英语的副作用?(分别)

我是JavaScript的新手,但我对闭包的工作原理感到困惑.有人可以用非专业人的术语解释它们是什么或为什么它们有用吗?

Alv*_*eto 15

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

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
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你 :-)