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
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.