js闭包

function f1() {
  var n = 999;
  nAdd = function () { n += 1 };
  function f2() {
          alert(n);
         }
  return f2;
}
var result = f1();
result(); // 999
nAdd();
result(); // 1000
闭包示例

Javascript内存回收机制是这样的:
“如果一个对象不再被引用,那么这个对象就会被GC回收。如果两个对象互相引用,而不再被第3者所引用,那么这两个互相引用的对象也会被回收。因为函数f1被nAdd引用,nAdd又被f1外的result引用,这就是为什么函数f1执行后不会被回收的原因。”

A closure is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).
  Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function.

(参考:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope#Nested_functions_and_closures)

也可以用setInterval或setTimeout来实现闭包

var outerFunc = function() {
var foo = 'success!';
setInterval(function(){alert(foo)}, 3000);
};

outerFunc();
setInterval和 setTimeout实现闭包

 

 

posted @ 2014-03-06 10:21  被爱浸润的智慧体  阅读(448)  评论(0编辑  收藏  举报