[英]ES6: Instantiate class without calling constructor
有什么方法可以在不調用其構造函數的情況下實例化新的類實例?
像這樣的東西:
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,並希望使用實體的構造函數來創建新對象,但不想在實例化已經持久化的對象(那些已經存儲在 DB 中的對象)的實體時調用它們。
我知道學說(PHP ORM)使用這種方法,但是他們正在使用代理類來實現它。 有沒有什么簡單的方法可以在打字稿(或通常在 ES6/ES7 中)實現這一點?
我已經找到了這個問題ES6: call class constructor without new keyword ,它要求相反,並看到一個提到Proxy
對象的答案。 這聽起來像是一種可能的方式,但從文檔中我不確定它是否可以實現。
您可以添加一個static
方法 create,從類原型創建一個 Object。 像這樣的東西應該工作:
class Test { constructor(foo) { this.foo = foo } static create() { return Object.create(this.prototype) } } 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.