如何使用ES6类动态初始化对象?
class AnObject{
constructor(name) {
this.name = name;
}
}
let p1 = new AnObject("name1");
console.log("p1 name: " + p1.name);
var className = "An" + "Object";
let p2 = new className("name2"); // Dynamically init an object?
console.log("p2 name: " + p2.name);
答案 0 :(得分:6)
通常的做法是将构造函数放在一个对象上,然后使用生成的字符串键在该对象上查找它们:
let ctors = {
AnObject: class {
constructor(name) {
this.name = name;
}
}
};
let className = "An" + "Object";
let p2 = new ctors[className]("name2");
console.log("p2 name: " + p2.name);
或者,我刚刚完成不推荐,您可以使用eval
:
class AnObject {
constructor(name) {
this.name = name;
}
}
let className = "An" + "Object";
let p2 = new (eval(className))("name2");
console.log("p2 name: " + p2.name)
或者更冗长,但可能更清楚:
let className = "An" + "Object";
let ctor = eval(className);
let p2 = new ctor("name2");
console.log("p2 name: " + p2.name)
只要您完全控制了您正在评估的字符串, eval
就可以了。但它在结构良好的代码中通常有点过分。