33

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;
Community
  • 1
  • 1
chris_mac
  • 943
  • 3
  • 10
  • 21
  • 1
    If this is what you think you'll need, then don't use variables for storage. Store `myObject` inside another object used as a global namespace. `var my_namespace = {}; my_namespace.myObject = new MyObject(); var myString = "myObject"; var itWorks = my_namespace[myString].myproperty` –  Jun 08 '12 at 17:28
  • @amnotiam My answer details what your comment is talking about, it's hard to understand it from a comment. – Ruan Mendes Jun 08 '12 at 18:14
  • I highly recommend this solution: http://stackoverflow.com/a/6394168/167129 – Dallas Clark Apr 23 '14 at 02:24
  • https://humanwhocodes.com/blog/2013/06/25/eval-isnt-evil-just-misunderstood/ – RooksStrife Aug 22 '18 at 19:51

4 Answers4

49

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
}
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • nice explanation.I am little confused on why we cant use the `Function` keyword in this case. http://stackoverflow.com/questions/36078655/extract-call-javascript-function-defined-in-the-onclick-html-attribute-of-an-e – techie_28 May 18 '16 at 09:45
  • @techie_28 You can, you just have to be careful with executing arbitrary code, just like `eval`. It's typically better to avoid it if possible. – Ruan Mendes May 18 '16 at 10:07
  • `Function(onclickB.replace("p,q", "p,q,r"))` this is working fine when `onclickB` is of the form `return someFunc(2,'abc')` but when I extract only the function name i.e. when `onclickB = 'someFunc'`,passing it to `Function(onclickB).call(....)` does not call the function & gives an error..am I doing something stupid here? – techie_28 May 18 '16 at 10:18
  • @techie_28 That's a separate question, you should create a new post so it's more useful to others... and link it here – Ruan Mendes May 18 '16 at 10:59
  • Please see http://stackoverflow.com/questions/37388085/function-typecasting-javascript – techie_28 May 23 '16 at 10:13
8

You can use the eval function.

eval(myString).myproperty

Careful with eval, though, if this is something the user is inputting, it will execute any javascript code!

sachleen
  • 30,730
  • 8
  • 78
  • 73
  • There are better ways (that others mentioned), don't use `eval` if you don't have to – Ruan Mendes Jun 08 '12 at 17:24
  • Yeah, I know eval shouldn't be used unless absolutely necessary and I just saw those. Did not know about that! +1 to those answers. – sachleen Jun 08 '12 at 17:26
7

The only way, as it seems to me, would be to use eval. But as they say, eval is evil - but not in controlled environments. This is the way it is possible, but i don't recommend using eval, unless it is absolutely necessary.

var myObject = new MyObject();
var myString = "myObject";
var wantThisToWork = eval(myString).myproperty;
Parth Thakkar
  • 5,427
  • 3
  • 25
  • 34
4

Use eval()

var myObject = {};
myObject.myproperty = "Hello";
var myString = "myObject";

var wantThisToWork = eval(myString).myproperty;
Anand
  • 14,545
  • 8
  • 32
  • 44
  • 5
    weren't multiple **eval** answers enough? This is exactly what i gave. – Parth Thakkar Jun 08 '12 at 17:31
  • 1
    Don't repost existing answers, there were already 3 answers like yours when you added it. Added no value to the post. – Ruan Mendes Jun 08 '12 at 17:32
  • @ParthThakkar : While, I was writing my answer and the time I posted it, already a hell many answers were posted. Some how notification for already posted answer did not come(slow internet). What made you think that I am interested in what you wrote ? – Anand Jun 08 '12 at 17:40
  • i didn't say that you were interested in what i wrote. I just said that that was exactly what i gave. Btw, aren't we all fighting over this small question for no reason. I mean, my answer is littered with my whines of someone downvoting it in spite of me warning about the answer....let's just leave this matter. It's being stretched unnecessarily. – Parth Thakkar Jun 08 '12 at 17:44
  • 1
    @JuanMendes : Every answer has been answered in 10 mins frame. This is how much time you would take, if you are dividing your time between watching football match and typing answer. Already posted message did not appear for me, so had no idea, that already answers were posted. – Anand Jun 08 '12 at 17:44
  • @ParthThakkar : ....and I gave my explanation. And I think for you, stackoverflow is only about upvote and downvote. Yes lets leave the matter.... – Anand Jun 08 '12 at 17:46
  • Too many duplicate answers and didn't even mention how dangerous is using eval in the anwer – zakir Oct 18 '19 at 10:56