Reputation: 1774
Consider this code:
var Someclass = new Class();
var Anotherclass = new Class();
var classes = ['Someclass', 'Anotherclass'];
and I want to create mootools class with a dynamic name. Of course i can do it by eval:
eval('var obj = new ' + classes[0] + '(params);');
but I do not think it is a good solution. How to do this in a "proper" way? Maybe somethink like:
var obj = ObjectFactory(classes[0], params);
Upvotes: 0
Views: 423
Reputation: 141879
Use the bracket notation to refer to the class as a string.
var object = new window['SomeClass']();
Pass it parameters as regular.
var object = new window['SomeClass'](1, 2, "three");
Instead of creating all classes globally, use an object to namespace them.
var My = {
SomeClass: new Class(..),
OtherClass: new Class(..)
};
var object = new My['SomeClass']();
Upvotes: 3