创建与现有实例相同的类的新实例,而不使用 eval()

问题描述 投票:0回答:1

我有一个未知类的实例

sampleInstance
,我需要创建同一类的第二个实例。这就是我现在正在做的事情:

  1. 我用
    sampleInstance.constructor.name
    查找班级名称。
  2. 接下来,我使用
    eval(`new ${sampleInstance.constructor.name}()`)
    创建同一类的新实例。

下面的代码工作正常:

class sampleClass_A { name = "Archimedes";}
class sampleClass_B { name = "Pythagoras";}

let sampleInstance = new sampleClass_A();

// later, in another part of the code, I don't know the constructor of sampleInstance anymore
let constructorName = sampleInstance.constructor.name
let newInstanceOfTheSameClass = eval(`new ${constructorName}()`); // how to do without eval()???
console.log(newInstanceOfTheSameClass .name); // "Archimedes"

但我宁愿不使用

eval()
。什么是更清洁的替代方案?

(我不能使用

window[constructorName]
,因为一般情况下这段代码不会在浏览器中运行。(甚至不确定它是否可以在浏览器中运行。))

typescript pointers constructor eval
1个回答
0
投票

直接调用构造函数!

const aCopy = new sampleInstance.constructor();
console.log(aCopy);
© www.soinside.com 2019 - 2024. All rights reserved.