您可以使用括号表示法来获取对象:
var items = {};
items.obj1 = {};
var type = 'obj1';
var myFunc = function(type){
var newObj = items[type]; //returns items.obj1
};
如何使用构造函数动态创建对象?
var Constructor1 = function() {};
var Constructor2 = function() {};
var type = 'Constructor2';
var myFunc = function(type){
var newObj = new type(); // how do you invoke either constructor?
};
最佳答案
在您的示例中,请尝试以下操作:
var myFunc = function(type) {
return new window[type]();
}
关于javascript - 根据字符串参数选择构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24131207/