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实现闭包

 

 

转载于:https://www.cnblogs.com/Gift/p/3583931.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值