Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: interpret string as object reference? [duplicate]

Tags:

javascript

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; 
like image 857
chris_mac Avatar asked Jun 08 '12 17:06

chris_mac


People also ask

Does JavaScript copy object by reference?

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.

Does JavaScript pass strings 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.

Why are objects copied by references?

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.

How do you know if two objects have the same reference?

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.


1 Answers

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 } 
like image 146
Juan Mendes Avatar answered Sep 22 '22 05:09

Juan Mendes