首页 > 解决方案 > 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对象。这听起来像是一种可能的方式,但从文档中我不确定它是否可以实现。

标签: javascriptnode.jstypescriptecmascript-6es6-class

解决方案


您可以添加一个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

推荐阅读