闭包概念 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.