Back

js中的 closure ( javascript closure)

发布时间: 2015-02-21 12:30:00

refer to :  http://www.w3schools.com/js/js_function_closures.asp and: http://www.ruanyifeng.com/blog/2009/08/learning_javascript_closures.html

w3school 给出的定义:  A closure is a function having access to the parent scope, even after the parent function has closed.

阮一峰的博客提到的是: 

各种专业文献上的"闭包"(closure)定义非常抽象,很难看懂。我的理解是,闭包就是能够读取其他函数内部变量的函数。

由于在Javascript语言中,只有函数内部的子函数才能读取局部变量,因此可以把闭包简单理解成"定义在一个函数内部的函数"。

所以,在本质上,闭包就是将函数内部和函数外部连接起来的一座桥梁。

最后看一个例子: 

var add = (function () {
  console.info('before in closure, counter: ' + counter);
  var counter = 0;
  return function () {
    console.info('in closure, counter: ' + counter);
    return counter += 1;
  }
})();

add();   # => before in closure, counter: undefined  
# => in closure, counter: 0
add();   # => in closure, counter: 1
add();   # => in closure, counter: 2
console.info('counter: ' + counter);    # => 这里会报错. 

只所以 var counter = 0 只运行一次,是因为 self invocation function  (IIEF) 只运行一次. 

Back