Javascript 根据字符串参数选择构造函数?

Javascript 根据字符串参数选择构造函数?,javascript,constructor,Javascript,Constructor,可以使用括号表示法获取对象: 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 = 'Co

可以使用括号表示法获取对象:

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]();
}

谢谢你的回答,它似乎与此相似;我要去看戏。很好,谢谢:)