Reputation: 745
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?
Upvotes: 1
Views: 1330
Reputation: 1153
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.
Upvotes: 1
Reputation: 1074028
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();
};
Upvotes: 3