调用嵌套匿名函数(JavaScript)

4

我是一个新手,对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();则什么都不记录?

为什么foo可以被访问,即使它应该超出范围,是因为JS使用了一些称为闭包的东西:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures - HMR
6个回答

5

调用parentFunction返回匿名函数而不是调用它。

nestedFunction被设置为parentFunction的返回值,即匿名函数。

因此,调用nestedFunction会调用匿名函数。

匿名函数使用console.log,因此您会看到"foo"


3

基本上你正在做:

parentFunction()(); // double parenthesis

括号表示执行函数,它会返回一个值。如果该值是一个函数,则可以执行它。

如果您只调用一次,那么您只会得到该函数,因此不会出现任何console.log


啊哈!这有道理。感谢您清晰简明的解释,也感谢所有回答的人。 - edubba

1
一个与你的代码类似的替代方案是这个。
var parentFunction = function() {
  var foo = "foo";
  return console.log.bind(console);
}

parentFunction()();
// => "foo"

不可避免地,您最终会想要在某个时候处理作用域,因此您可以像这样进行操作:

var parentFunction = function() {
  this.foo = "foo";
  this.something = function(){
    console.log(this.foo);
  }
  return this.something.bind(this);
}

parentFunction()();
// => "foo"

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

解释:

当调用add函数时,它返回一个函数。 该函数关闭上下文并记住参数x在那个时间(即上面代码中的5)。 当将调用add函数的结果分配给变量add5时,它将始终知道最初创建时x是什么。 上面的add5变量指的是一个函数,它将始终将值5添加到发送的内容中。 这意味着当使用值3调用add5时,它将把5与3相加,并返回

请参考此链接...

http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/


0
因为parentFunction返回了嵌套函数,需要调用该函数才能运行。
var a = nestedFunction;

没有记录任何内容,因为它还没有被执行,直到你执行以下操作:

a();

0

将那段代码改写成这样:

var nestedFunction = null;

var parentFunction = function() {
    var foo = 'foo';
    nestedFunction = function() { // anonymous function being returned
        console.log(foo); // logs 'foo'
    }
}

parentFunction(); 
// outputs nothing
// but initializes nestedFunction by its local function

nestedFunction(); /* logs foo because that local function has access to local 'foo' of
the parent function */

正如您所见,父函数没有输出任何内容,只是通过函数引用初始化了嵌套函数变量。而该函数引用可以像其他函数一样被调用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接