Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinguishing closure and local variables

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

like image 600
lockedscope Avatar asked Feb 27 '10 15:02

lockedscope


People also ask

What are closure variables?

A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time the closure was created.

What is the difference between closure and scope?

Whenever you create a function within another function, then the inner function is closure. This closure is usually returned so you can use the outer function's variables at a later time. Whereas a scope in JavaScript defines what variables you have access to.

What is a closure in functional programming?

A closure is a programming technique that allows variables outside of the scope of a function to be accessed. Usually, a closure is created when a function is defined in another function, allowing the inner function to access variables in the outer one.

How do you define a local variable?

A local variable is a variable that is only accessible within a specific part of a program. These variables are usually local to a subroutine and are declared or defined within that routine. Parameters that are defined by value can also be considered as local variables.


1 Answers

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".

like image 195
Ben Zotto Avatar answered Oct 04 '22 06:10

Ben Zotto