如何从其他函数返回函数然后调用它?

时间:2015-11-03 11:21:59

标签: javascript closures

有人可以解释为什么下面的代码失败了吗? 我如何使用闭包访问zip函数?我希望它能打印出value1

function foo() {
    var bar;

    function zip() {
        var quux = 'value1';
        bar = true;    
        console.log(quux);
    }

    quux = 'value2';
    console.log(quux);
    return zip;      
}

foo();

var a = zip;

a();

目前正在说zip is not defined

2 个答案:

答案 0 :(得分:5)

您可以使用:

foo()()

或与变量赋值相同:

var a = foo();
a();

请注意,它会同时输出value2value1.

这是如何工作的?

为了更容易理解提供的代码,请考虑以下示例,该示例与您的代码产生相同的结果:

function foo() {
  var bar;
  quux = 'value2';
  console.log(quux);

  return function() {
    var quux = 'value1';
    bar = true;

    console.log(quux);
  };
}

var a = foo(); // executes code, returns function and stores it in a variable
a(); // executes function, stored in a variable

我想,现在更容易理解这段代码 - 它执行一些代码,返回一个函数,稍后再调用。

现在,考虑另一个例子:

function foo() {
  var bar;
  quux = 'value2';
  console.log(quux);

  var zip = function() {
    var quux = 'value1';
    bar = true;

    console.log(quux);
  };

  return zip;
}

var a = foo(); // executes code, returns function and stores it in a variable
a(); // executes function, stored in a variable     

此代码执行相同操作,但它在返回结果之前将函数存储在变量中。您在示例中提供的代码几乎与上一个示例没有区别,但函数声明除外:

这几乎是等价的(why almost?):

var zip = function() {
};

function zip() {
}

答案 1 :(得分:0)

功能' foo'正在退回' zip'功能但未调用(例如:zip())。因此,您可能必须在变量中捕获返回的函数。

var f = foo();

然后致电:

f();

输出:

value2
value1
相关问题