Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to access a function local variable from outside of the function?

I heard today that "it is possible to access a local variable of a function since everything in javascript is global".

As far as I know, you can't access a local variable from outside of the scope of the variable.

For example,

function f()
{
    var myvar = "something";
}

myvar = "c"; // i'm not accessing myvar in f();

I also heard that it's possible to use for(var i in window) to access myvar. I want to confirm it is not possible since I'm not the author of the language.

Updated:

I asked him a code snippet, and here's what I have received.

var person = {
    whoIs : function()
    {
        var name = "name";
        return name;
    }
};


var str = "TEST:\n";

for(var n in person)
{
    str += n;
    str += " = [" + person[n] + "]\n";
}

// perform regular exp. to get the value of name variable.


alert(str);

It's not accessing the variable.........it's simply printing how the function looks like...

like image 777
Moon Avatar asked Dec 02 '22 00:12

Moon


1 Answers

That developer was wrong. Those two myvar are different. The outside one is equivalent to window.myvar, but the inside one is only inside the f.

Edit: a very simple example: http://jsfiddle.net/mRkX3/

Edit 2:

A quote from the ECMAScript standard:

If the variable statement occurs inside a FunctionDeclaration, the variables are defined with function-local scope in that function, as described in section 10.1.3. Otherwise, they are defined with global scope (that is, they are created as members of the global object, as described in section 10.1.3) using property attributes { DontDelete }. Variables are created when the execution scope is entered. A Block does not define a new execution scope. Only Program and FunctionDeclaration produce a new scope. Variables are initialised to undefined when created. A variable with an Initialiser is assigned the value of its AssignmentExpression when the VariableStatement is executed, not when the variable is created.

Found through http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting though that article is referencing a deadlink (live link: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf).

like image 156
Corbin Avatar answered Dec 04 '22 10:12

Corbin