Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Get access to local variable or variable in closure by its name [duplicate]

Possible Duplicate:
How can I access local scope dynamically in javascript?

Hi all.
We all know that you can access a property of a javascript object by it's name using the [] syntax.. e.g. ob['nameOfProperty'].

Can you do the same for a local variable? Another answer here suggested the answer is to use window['nameOfVar']. However, this only worked for the poster as he was defining variables at window-level scope.

I assume that this must be possible in general, as Firefox's Firebug (which I believe is written in javascript) can show local and closure variables. Is there some hidden language feature I'm not aware of?

Specifically, here's what I want to do:

 var i = 4;
 console.log(window['i']); // this works..

 function Func(){
     var j = 99;

     // try to output the value of j from its name as a string
     console.log(window['j']); // unsurprisingly, this doesn't work
 }

 Func();
like image 669
Ben Clayton Avatar asked Feb 25 '10 18:02

Ben Clayton


4 Answers

I'm not aware of anything built into JavaScript to reference local variables like that (though there probably should be considering all variables are internally referenced by strings).

I'd suggest keeping all your variables in an object if you really need to access by string:

var variables = {
    "j": 1
};
alert(variables["j"]);

Update: It kind of bugs me that there's no way to do this like you want. Internally the variable is a mutable binding in the declarative environment records. Properties are bound to the object they're a property of through the object's environment records, but there's actually a way to access them using brackets. Unfortunately, there's no way to access the declarative environment records the same way.

like image 148
Bob Avatar answered Nov 15 '22 13:11

Bob


Accessing the variable with window or any other global accessor won't work because the variable is not globally accessible. But you can use can use eval to evaluate any expression:

<script>
function test(){
   var j = 1; 
   alert(eval("j"));
}

test();
</script>
like image 30
PanJanek Avatar answered Nov 15 '22 13:11

PanJanek


What about:

<script>
    function Func(){
        var fn = arguments.callee;
        fn.j = 99;
        console.log(fn['j']);
    }
    Func();
    console.log(window['j']); //not global
    console.log(Func['j']); //but not private
</script>
like image 2
Mic Avatar answered Nov 15 '22 14:11

Mic


No, this isn't possible in general. JavaScript resolves identifiers inside a function using the scope chain; there's no single object that contains all the variables in scope, and the objects in the scope chain are inaccessible from JavaScript running in the page.

like image 2
Tim Down Avatar answered Nov 15 '22 15:11

Tim Down