Possible Duplicate:
Javascript use variable as object name
How do I get JS to treat a string as a reference to a previously defined object? Simplified:
var myObject = new MyObject(); var myString = "myObject"; var wantThisToWork = myString.myproperty;
Objects and ArraysObjects in JavaScript are passed by reference. When more than one variable is set to store either an object , array or function , those variables will point to the same allocated space in the memory. Passed by reference.
In fact, Strings in Javascript are indeed passed “by reference”. Thus, calling a function with a string does not involve copying the string's contents. However, JavaScript Strings are immutable; in contrast to C++ strings, once a JavaScript string has been created it cannot be modified.
Objects are assigned and copied by reference. In other words, a variable stores not the “object value”, but a “reference” (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object itself.
For reference type like objects, == or === operators check its reference only. here a==b will be false as reference of both variables are different though their content are same. and if i check now a==b then it will be true , since reference of both variable are same now.
If the variable is in the global scope, you can access it as a property of the global object
var a = "hello world"; var varName = "a"; console.log( window[varName] ); // outputs hello world console.log( this[varName] ); // also works (this === window) in this case
However, if it's a local variable, the only way is to use eval
(disclaimer)
function () { var a = "hello world"; var varName = "a"; console.log( this[varName] ); // won't work console.log( eval(varName) ); // Does work }
Unless you can put your dynamic variables into an object and access it like a property
function () { var scope = { a: "hello world"; }; var varName = "a"; console.log( scope[varName] ); // works }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With