【问题标题】:Getting class name of instance and using it to create new instances in JS [duplicate]获取实例的类名并使用它在JS中创建新实例[重复]
【发布时间】:2021-04-29 01:24:20
【问题描述】:

我有许多不同类的实例,我想随机选择其中任何一个(比如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();

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

有办法绕过去吗?

【问题讨论】:

    标签: javascript class instance instanceof


    【解决方案1】:

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

    class Test {
      constructor() {
        console.log("constructing a Test");
      }
    }
    
    inst1 = new Test();
    cls = inst1.constructor;
    inst2 = new cls;

    【讨论】:

      猜你喜欢
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多