Javascript之闭包理解

闭包概念 An inner function always has access to the vars and parameters of its outer function, even after the outer function has returned…

内部函数始终可以访问外部函数的变量及参数,即使外部函数被返回。

由于外部函数不能访问内部函数(js作用域链,大家懂的),但是有时候需要在外部访问内部函数中的变量。相反,因为内部函数可以访问外部变量,因此一般是在函数中嵌套一个内部函数,并返回这个内部函数,在这个内部函数中是可以访问父变量对象中的变量的。所以通过返回内部函数,那么在全局作用域中就可以访问函数内部的变量了。为了简单理解,还是赶紧给出example咯:

function foo() {
    var a = 'private variable';
    return function bar() {
        alert(a);
    }
}
var callAlert = foo();

callAlert(); // private variable

// Global Context when evaluated
global.VO = {
    foo: pointer to foo(),
    callAlert: returned value of global.VO.foo
    scopeChain: [global.VO]
}

// Foo Context when evaluated
foo.VO = {
    bar: pointer to bar(),
    a: 'private variable',
    scopeChain: [foo.VO, global.VO]
}

// Bar Context when evaluated
bar.VO = {
    scopeChain: [bar.VO, foo.VO, global.VO]
}

By alerting a, the interpreter checks the first VO in thebar.VO.scopeChain for a property named a but can not find a match, so promptly moves on to the next VO, foo.VO.

It checks for the existence of the property and this time finds a match, returning the value back to the bar context, which explains why thealert gives us 'private variable' even though foo() had finished executing sometime ago.

By this point in the article, we have covered the details of thescope chain and its lexical environment, along with how closures andvariable resolution work. 

参考: 看看这篇文章

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值