1

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

Paul
  • 26,170
  • 12
  • 85
  • 119
Kamafeather
  • 8,663
  • 14
  • 69
  • 99
  • 2
    the first `bar` returns a function (that you never execute, which is why you see nothing), while the second returns the *result* of executing `ra`. – Andrew Whitaker Dec 10 '13 at 19:00

1 Answers1

3
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();
};
Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
  • thanks, that's interesting! So I was not calling the *foobar()* function. Is there any article where I can understand better why the interpreter is not executing the function while calling the *return*? – Kamafeather Dec 10 '13 at 19:22
  • @Pictor - sorry, I missed this comment. Umm, not really. Just remember that functions are first class citizens in JavaScript. You can pass them into, and return them from other functions. So when you say return function(){} you're returning a function, just like that. It's no different from saying return 0; The 0 isn't getting executed any more than the function; both are simply being returned as is. – Adam Rackis Dec 11 '13 at 06:12