Double nesting a function-valued return stops from entering the double nested function

非 Y 不嫁゛ 提交于 2019-12-24 12:18:44

问题


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


回答1:


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();
};


来源:https://stackoverflow.com/questions/20502954/double-nesting-a-function-valued-return-stops-from-entering-the-double-nested-fu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!