tags:

views:

68

answers:

3

I have a simple factory below that I would like to simplify and not be required to modify each time I add a new object that I would like to return. In Javascript, how would I be able to create an object at runtime? Thanks

switch (leagueId) {
  case 'NCAAF' :
      return new NCAAFScoreGrid();
  case 'MLB' :
      return new MLBScoreGrid();
  ... 
}
A: 

you can use eval method for example,

return eval("new "+leagueId+"ScoreGrid();");

eval will evaluate code at runtime and will return the object.

jatanp
I am actually developing using a TV framework that prevents the use of eval.
Steve
eval is unnecessary here
Mike Samuel
eval is evil and should be avoided.
Jesper
+5  A: 
var leagues = {
    'NCAAF': NCAAFScoreGrid,
    'MLB':   MLBScoreGrid,
    // ...
};  // maybe hoist this dictionary out to somewhere shared

if (leagues[leagueId]) {
    return new leagues[leagueId]();
}
// else leagueId unknown
ephemient
Thanks. I like this idea.
Steve
+1  A: 

You can use the bracket operator to look-up the constructor.

new (window[leagueId + 'ScoreGrid'])(...);
Mike Samuel
I wish this worked as this seems to be the cleanest solution, but unfortunately I am using Javascript in an embedded TV environment and there is no root window object.
Steve