Javascript之闭包理解

来源:互联网 发布:java jdbc 连接 编辑:程序博客网 时间:2024/06/04 20:13

闭包概念 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 evaluatedglobal.VO = {    foo: pointer to foo(),    callAlert: returned value of global.VO.foo    scopeChain: [global.VO]}// Foo Context when evaluatedfoo.VO = {    bar: pointer to bar(),    a: 'private variable',    scopeChain: [foo.VO, global.VO]}// Bar Context when evaluatedbar.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. 

参考:看看这篇文章

1 0
原创粉丝点击