微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决获取实例的类名并使用它在 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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。