简体   繁体   English

如何从另一个函数返回一个函数然后调用它?

[英]How do I return a function from another function and then call it?

Can someone explain why the code below fails? 有人可以解释为什么下面的代码失败吗?
How i can access the zip function using closures? 我如何使用闭包访问zip函数? I want it to get it to print out value1 . 我希望它打印出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();

It is currently saying zip is not defined . 目前说zip is not defined

You can use: 您可以使用:

foo()()

or the same with assignment to a variable: 或分配给变量的方法相同:

var a = foo();
a();

Note that it will output both value2 and then value1. 请注意,它将同时输出value2value1.

How is this working? 这如何运作?

In order to make it easier to understand the provided code, consider the following example which makes the same result as your code: 为了使您更容易理解提供的代码,请考虑以下示例,该示例的结果与您的代码相同:

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

I guess, it is easier to understand this code now - it executes some code, returns a function, which you call later. 我猜想,现在更容易理解该代码-它执行一些代码,返回一个函数,稍后再调用。

Now, consider another example: 现在,考虑另一个示例:

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     

This code does the same, but it stores a function in a variable before returning as result. 该代码执行相同的操作,但是在将结果返回之前,将函数存储在变量中。 The code that you have provided in example almost does not differ from the last example, except for function declaration: 您在示例中提供的代码与上一个示例几乎没有什么不同,除了函数声明:

These are almost equivalent ( why almost? ): 这些几乎是等效的( 为什么要这样? ):

var zip = function() {
};

function zip() {
}

The function 'foo' is returning the 'zip' function but not called(ex: zip()). 函数“ foo”返回“ zip”函数,但未调用(例如:zip())。 Hence you may have to capture the returning function in a variable. 因此,您可能必须将返回函数捕获到变量中。

var f = foo();

Then call: 然后致电:

f();

Output: 输出:

value2
value1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM