JavaScript Functions that return function

This question already has an answer here:

  • How do JavaScript closures work? 88 answers
  • Why do you need to invoke an anonymous function on the same line? 19 answers

  • Let's decompose the statements in its constituents:

    var xx =(function(){var e = 0; return function(){return e++}})();
    
  • var e = 0; assign 0 to e

  • return function(){return e++;}

    return a function f which:

    2.1 return the value of e

    2.2 increment e by 1

  • var xx = function(){var e = 0; return function(){return e++}})();

    assign to xx the function f(){ return e++} with scope [e=0]

  • xx();

    Exec the function f:

    4.1 return the value of e // 0

    4.2 increment e by one // e = 1

    4.3 xx is now the function f(){ return e++; } with scope [e=1]

  • So, xx is the function which return the internal value of e (starting from 0 ) and increment e by one.

    IF you call xx(); another time, you'll get:

    xx(); // returns 1
    xx = f(){ return e++;}[e=2] // returns 2 and increment e by one
    

    yes, it is returning function, and every time you execute this function xx(); it will return an incremented value

    alert( xx() ); //will alert 0

    alert( xx() ); //will alert 1

    alert( xx() ); //will alert 2

    Hope this answers the question


    In JavaScript, functions are first-class objects; that is, they can be passed around and assigned to variables like anything else. So in your case xx is simply a reference to the inner function which can be called, passed around further etc.

    One benefit of doing so means you can implement private variables like in your example. By defining e inside the outer function, and referencing it inside the inner function, the inner function retains that reference to e even after it is returned. This allows you to call

    xx();
    xx();
    xx();
    

    which will increment and return the value of e each time. You can't override this variable since there's no public reference to it.

    链接地址: http://www.djcxy.com/p/1486.html

    上一篇: 在下面的例子中JavaScript闭包如何工作?

    下一篇: JavaScript函数返回函数