I have a pretty straight forward question, however I can't seem to find a solution for it anywhere...

Basically I would like to instantiate a new Javascript object, but the class name is a variable. In PHP the implementation is fairly straight forward new $className(). I have tried the following solution in Javascript, without luck:

window.onload=function(){
function obj(){
    this.show = function(){
        console.log('Hallo World');
    }
}

var objs = ['obj'];

new objs[0]().show();
} 

Does anyone know how to pull this off?

有帮助吗?

解决方案

With the code as shown, you can't do it without eval.

If you're willing to change it, you can:

window.onload=function(){
    var things = {
        obj: function(){
            this.show = function(){
                console.log('Hallo World');
            };
        }
    };

    new things['obj']().show();
    // Or: new things.obj().show();
};

其他提示

Will this help you:

var creator = {
    obj : function (){
        this.show = function(){
        console.log('Hallo World');
        };
    }
}
var myInstance = new creator['obj'];
myInstance.show();

The idea is to define the constructor as a property.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top