Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
699 views
in Technique[技术] by (71.8m points)

javascript - 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:
";

for(var n in person)
{
    str += n;
    str += " = [" + person[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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...