Javascript closure returning recursive function

I am new to Javascript and functional paradigms. I really like to use closure to keep small bits of state safely closed in enclosed space. This is a refreshing change from the song and dance of class worship in Java.

I wrote the following code with the intention of printing 0-9 on the console. It works, but I'm surprised that it is.

I don’t understand how it nextrefers to the returned function for a recursive call next()! Is this related to the Javascript late binding attribute?

var next = (function() {  // begin stateful wrapper function
    var current = -1;

    return function() {   // begin returned function
        current += 1;
        if (current < 10) {
            console.log(current);

            next();       // recursive call 
        } else {
            return;
        }
    };    // end returned function

})();     // immediately call wrapper function

next();   // call returned function to generate output
  • At runtime, how does the recursive next () call already refer to the returned function?

  • Where can I read the details of what is happening here?

(Output:)

0
1
2
3
4
5
6
7
8
9
+4
2

, , . current . , , , .

var current = -1;
var next = function() {// This is what would have been returned in the original
    current += 1;
    if (current < 10) {
        console.log(current);

        next();       // recursive call 
    } else {
        return;
    }
};

next();

, , , current . , next.


, , , . next, return .


JavaScript (), , , :

var next;

{ // Create a (fictional) variable scope that has `current` and the function

    var current = -1;

    next = function() {
        current += 1;
        if (current < 10) {
            console.log(current);

            next();       // recursive call 
        } else {
            return;
        }
    };

}

next();

JS , , .

, .

var next;

(function() { // Create a variable scope that has `current` and the function

    var current = -1;

    next = function() {
        current += 1;
        if (current < 10) {
            console.log(current);

            next();       // recursive call 
        } else {
            return;
        }
    };

}());

next();
+4

, recursive next() ?

, next ( })(); // immediately call wrapper function), ( - JavaScript ), next , . (next();) , next next.

AFAIU, " " , this .

next , , ( next , undefined , JavaScript, , var - ).

( ( , ): ( " " ) , next, var, . , var, , , , next , var , ( this, ).)

, ?

: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

UPDATE

:

JavaScript...

  • ( ) var, undefined ( ) ( , , ) , , ( ). , window.myFunc = function () {};.
  • ​​ var function myName () {}, . var, , , , .
  • , var, , , myGlobal = function () {};, ( # 1 ) " " , .
+1

Source: https://habr.com/ru/post/1529514/


All Articles