0

I need to create a new instance of a class whose name is dynamically built by:

eval('SomeObject.'+id+' = new SomeClass'+Data.type+'(id, Data);');
// results in:
SomeObject._123 = new SomeClassWithDynamicName(id, Data);

it works fine, but i'd rather avoid the usage of eval (its almost impossible to track errors in code after an eval occured) and do something like this:

SomeObject[id] = new ('SomeClass'+Data.type)(id, Data);
RienNeVaPlu͢s
  • 7,442
  • 6
  • 43
  • 77

2 Answers2

2

Try this :

var SomeObject[id] = window['SomeClass'+Data.type];
SomeObject[id].setId(id);
SomeObject[id].setData(Data);

UPDATE : You can also try this if you don't have setters:

var SomeObject[id] = window['SomeClass'+Data.type](id, Data);

There is a similar question here : Instantiate a JavaScript Object Using a String to Define the Class Name

Community
  • 1
  • 1
Akram Fares
  • 1,653
  • 2
  • 17
  • 32
1

Do you really need to declare the classes globally as such? This would be a non-issue if you could register them on an object, like:

var classes = {};
classes.Type1 = function (id, data) { ... }
classes.Type2 = function (id, data) { ... }

var type = 'Type1';
var instance = new classes[type](id, data);
numbers1311407
  • 33,686
  • 9
  • 90
  • 92