hamczu
hamczu

Reputation: 1774

How to create MooTools class of a variable name

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

Answers (1)

Anurag
Anurag

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

Related Questions