有没有办法在不调用构造函数的情况下实例化一个新的类实例?
就像这样:
class Test {
constructor(foo) {
this.foo = 'test';
}
}
const a = new Test('bar'); // call constructor
const b = Test.create(); // do not call constructor
console.log(a.foo, a instanceof Test); // bar, true
console.log(b.foo, b instanceof Test); // undefined, true
我正在尝试开发TS mongo ORM,并希望使用实体的构造函数来创建新对象,但不想在实例化已持久化对象的实体时调用它们(那些已经存储在数据库中的实体)。
我知道doctrine(PHP ORM)使用这种方法,但据我所知,他们使用代理类来实现它。在typescript(或一般的ES6 / ES7)中是否有任何简单的方法可以实现这一点?
我已经找到了这个问题ES6: call class constructor without new keyword,它要求相反,并看到一个答案提到
Proxy
对象。这听起来像是一种可能的方法,但从文档中我并不确定它是否可行。