gpt4 book ai didi

javascript - ES6 : Instantiate class without calling constructor

转载 作者:搜寻专家 更新时间:2023-10-30 22:06:19 25 4
gpt4 key购买 nike

有什么方法可以在不调用其构造函数的情况下实例化新类实例吗?

像这样:

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目的。这听起来像是一种可行的方法,但从文档中我不确定它是否可以实现。

最佳答案

您可以添加一个 static 方法 create,它从类原型(prototype)创建一个对象。类似的东西应该可以工作:

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

关于javascript - ES6 : Instantiate class without calling constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50856341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com