调用嵌套匿名函数(javascript)

问题描述 投票:3回答:7

我是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();则什么都不会记录?

javascript
7个回答
3
投票

基本上是您正在做的:


4
投票

调用parentFunction会返回匿名函数


1
投票

您的代码的替代方法是此


1
投票
function add (x) {
    return function (y) {
        return x + y;
    };
}
var add5 = add(5);
 add5(3);

0
投票

因为parentFunction返回嵌套函数,需要运行该嵌套函数才能运行。


0
投票

以这种方式重写该代码:


0
投票

这是我从在线教程中学到的:

© www.soinside.com 2019 - 2024. All rights reserved.