获取实例的类名并使用它在 JS 中创建新实例

问题描述

我有许多不同类的实例,我想随机选择它们中的任何一个(例如 inst1)并创建所选实例类的新实例(例如 cls1)。 这就是我实施它的方式:

// getting class name of selected instance (say inst1),i.e. clsName is cls1
let clsName = inst1.constructor.name;

// use the class name obtained above to create new instance
let newInst = new clsName();

但它给了我错误的说法; “未捕获的类型错误:clsName 不是 HTMLDocument 中的构造函数

有没有办法绕过?

解决方法

claName 是一个字符串,而不是一个函数。构造函数是inst1.constructor,调用那个。

class Test {
  constructor() {
    console.log("constructing a Test");
  }
}

inst1 = new Test();
cls = inst1.constructor;
inst2 = new cls;