javascript - TS/ES6:实例化类而不调用构造函数
问题描述
有什么方法可以在不调用其构造函数的情况下实例化新的类实例?
像这样的东西:
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
推荐阅读
- java - 如何修复 tomcat org.apache.tomcat.util.http.parser.HttpParser。
字符 [[] 不被允许,将继续被拒绝 - javascript - ShadowRoot 以 Null 形式返回 - ShadowRoot 显示为打开
- r - R for循环,如何在每次迭代的循环外存储数据帧以避免性能下降
- java - 不止一个包名称为“android.support.graphics.drawable”的库
- julia - 如何在 Julia 1.0.0 中访问 conv 函数
- android - android在styles.xml中设置自定义属性并进入程序
- c++ - 如何在运行时在 C++ 对象数组中动态追加新对象并打印它们
- java - 如何在equals()中可扩展地考虑空值?
- javascript - Elasticsearch javascript 文件无法加载
- mysql - 在 mySQL 中将返回值格式化为小数点后 2 位