首页 > Web开发 > 详细

js闭包

时间:2014-03-06 22:21:35      阅读:454      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
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来实现闭包

bubuko.com,布布扣
var outerFunc = function() {
var foo = ‘success!‘;
setInterval(function(){alert(foo)}, 3000);
};

outerFunc();
setInterval和 setTimeout实现闭包

 

 

js闭包,布布扣,bubuko.com

js闭包

原文:http://www.cnblogs.com/Gift/p/3583931.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!