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

Select a constructor function based on a string parameter?

本文关键字:选择 构造函数 参数 字符串      更新时间:2023-09-26

你可以使用括号来获取一个对象:

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