我是Java语言和程序设计的新手,来自一本名为Javascript Enlightenment(p.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();
则什么都不会记录?
基本上是您正在做的:
调用parentFunction
会返回匿名函数
您的代码的替代方法是此
function add (x) {
return function (y) {
return x + y;
};
}
var add5 = add(5);
add5(3);
因为parentFunction
返回嵌套函数,需要运行该嵌套函数才能运行。
以这种方式重写该代码:
这是我从在线教程中学到的: