[英]Javascript instantiate object with variable name
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. 基本上我想实例化一个新的Javascript对象,但类名是一个变量。 In PHP the implementation is fairly straight forward
new $className()
. 在PHP中,实现是相当直接的
new $className()
。 I have tried the following solution in Javascript, without luck: 我在Javascript中尝试了以下解决方案,没有运气:
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
. 使用如图所示的代码,如果没有
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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.