我是一个新手,对Javascript和编程一般都不太了解,从一本名为《Javascript Enlightenment》(第88页)的书中看到了下面这段代码:
var parentFunction = function() {
var foo = 'foo';
return function() { // anonymous function being returned
console.log(foo); // logs 'foo'
}
}
// nestedFunction refers to the nested function returned from parentFunction
var nestedFunction = parentFunction();
nestedFunction(); /* logs foo because the returned function accesses foo
via the scope chain */
为什么设置
var nestedFunction = parentFunction();
使得nestedFunction();
能够调用嵌套的匿名函数并将"foo"记录到控制台,而仅使用parentFunction();
则什么都不记录?