2

Hard to explain.. I basicly want to do the following:

var doWhat = "speak";

var speak = {
    hello: function() { alert: "Hello!"; }
};

// Won't work
doWhat.hello();

It's a bad example, but you should be able to get what I mean. Is it possible somehow ?

4
  • I don't think it's either of those, too. I think what we want here, is have multiple objects with the same "interface", and instantiating an object to either of those using the name. Commented Jan 15, 2012 at 13:50
  • What is the underlying problem you're trying to solve? What, in other words, leads you to the point where you feel that this is a key stumbling block? If we take a few steps back, it might be possible to propose a more idiomatic way of doing what you need to do. Commented Jan 15, 2012 at 13:51
  • @MiladNaseri then how come any valid answer to this will be exactly the same as any valid answer to any of the millions of duplicates. You either use [] access or eval. Nothing to see here imo. Commented Jan 15, 2012 at 14:57
  • Fair question. I just know that the questions aren't exactly the same, but if you evaluate them by their answers ... this is going too much into hermeneutics for me. You do have a good point though. Commented Jan 15, 2012 at 15:01

3 Answers 3

1

You can use eval(doWhat).hello();. That way the contents of doWhat will be evaluated to the object reference.

Sign up to request clarification or add additional context in comments.

4 Comments

Yes this will work, but eval() is generally considered a really bad thing to use. There are probably other, better ways to solve the underlying problem.
Agreed, but in a closed environment when you can ensure that no tampering occurs, it's still safe to use eval.
Mh, thanks. Now what do I do when I want to get an objects variable using this method ? obj.eval(str) does not work.. :/
No, you just do obj[str] to access an object's fields dynamically.
1

You can do something like

var doWhat = {}, str = "speak";

doWhat[str] = {
    hello : function() {}
}; 

doWhat[str].hello();

1 Comment

... or doWhat[ someVariable ].hello(); ...
0
jsName = 'PageIndexController';

//ST1
eval("if( typeof jsName === 'undefined')alert(111);");

//ST1
eval("if( typeof " + jsName + " === 'undefined')alert(222);");

//ST1 not work
//ST2 work and the output: 222;

//there are two different way using eval, we will get 2 different outcome.

Comments