Frage

Trying to understand the scope chain and execution context stack articles from David Shariff's Blog, I've tried to understand closures here

function foo() {
    var a = 'private variable';
    return function bar() {
        alert(a);
    }
}

var callAlert = foo();
callAlert(); // private variable

I just wanted to test if inner function has the variable object just from its parent or from the whole scope chain, so I added a nested function repeating the example:

function foo() {
    var a = 'private variable';
    return function bar() {
        return function foobar() {
            console.log(a);
        };
    };
}

var callAlert = foo();
callAlert();  //

And that is not giving any result. It seems the interpreter is not even entering the foobar() function. And the syntax is the same than its parent.

But it works if I divide the function declaration and execution.

function foo() {
    var a = 'private variable';
    return function bar() {
        function ra() {
            console.log(a);
        };
        return ra();
    };
}

var callAlert = foo();
callAlert(); // private variable

And really I'm trying to guess why; where's the difference from bar() and foobar() functions.

PS - I'm testing on JSFiddle

War es hilfreich?

Lösung

function foo() {
    var a = 'private variable';
    return function bar() {
        return function foobar() {
            console.log(a);
        };
    };
}

Here you're returning a function that returns a function, so you need to call that new, doubly nested function

var callAlert = foo()();

DEMO

Or any variation on that theme

var getBar = foo();
var getFooBar = getBar();
getFooBar(); //private variable.

Updated demo


The second example works fine because you're still returning one function—a function that simple calls another function.

return function bar() {
    function ra() {
        console.log(a);
    };
    return ra();
};
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top