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 ?

  • 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. – Milad Naseri Jan 15 '12 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. – Pointy Jan 15 '12 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. – Esailija Jan 15 '12 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. – Milad Naseri Jan 15 '12 at 15:01

3 Answers3

1

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

Milad Naseri
  • 4,053
  • 1
  • 27
  • 39
  • 1
    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. – Pointy Jan 15 '12 at 13:50
  • Agreed, but in a closed environment when you can ensure that no tampering occurs, it's still safe to use eval. – Milad Naseri Jan 15 '12 at 13:54
  • Mh, thanks. Now what do I do when I want to get an objects variable using this method ? obj.eval(str) does not work.. :/ –  Jan 15 '12 at 14:54
  • No, you just do `obj[str]` to access an object's fields dynamically. – Milad Naseri Jan 15 '12 at 14:58
1

You can do something like

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

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

doWhat[str].hello();
stecb
  • 14,478
  • 2
  • 50
  • 68
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.
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
VicIT
  • 1
  • 1