Skip to content Skip to sidebar Skip to footer

Double Nesting A Function-valued Return Stops From Entering The Double Nested Function

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 va

Solution 1:

functionfoo() {
    var a = 'private variable';
    returnfunctionbar() {
        returnfunctionfoobar() {
            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.

returnfunctionbar() {
    functionra() {
        console.log(a);
    };
    returnra();
};

Post a Comment for "Double Nesting A Function-valued Return Stops From Entering The Double Nested Function"