views:

94

answers:

3

A local function in the closure declares a variable with the same name which exists in the closure. So, how could we access closure's variable from the local function?

function closure()
{
    var xVar; 
    function func1()
    {
        var xVar;
        // how to distinguish local and closure scopes.
        return xVar;
    }
    return function () { return func1(); };
}

Creating a private object and making private variables as properties of this object could help. But I am wondering if there is a better and neat solution. Can a scope chain help?

I have edited to make it a complete closure. Anyway, closures are not much concern here, it could be considered for inner functions however, there may be a solution with closures somehow.

Thanks

A: 

In your example the xVar variable is not a closure, because you redefined its scope to each function. To use that variable as a closure continue to declare it with the var command in the closure() function and then do not declare it with the var function in the func1() function. Instead just use the variable immediately in func1().

There is not an easy way to test if a function is a closure or a local variable. You would have to perform some sort of flow control test and then analyze assignments, where assignments occur, and where assignments do not occur. Then you must compare those results. You could write a tool, in JavaScript, to perform that analysis upon a given input and write you a report as output.

I think that he knows that. The question is, from code inside "func1" how would you refer explicitly to the "xVar" defined in "closure" (and not the "xVar" defined in "func1")?
Pointy
I answered that in my first paragraph.
+1  A: 

Variables defined in an inner scope hide variable declarations in an outer scope. The "better and neat solution" is not to reuse variable names that way.

JSBangs
+2  A: 

You can't access the scope chain explicitly in JS. Your problem is the age-old one of variable shadowing, but it's that much more maddening because in JS, the scope chain is actually there at runtime, it's just not available for you to access.

You can play some tricks with rejiggering current scope if you use the hated with operator, but that (as well as arguments's caller/callee stuff) really just give you access to objects and functions with their properties. There's no way to say "give me what xVar means in the n-1 runtime scope from right here".

quixoto