문제

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);
도움이 되었습니까?

해결책

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']();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top