Вопрос

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