ES6:在不调用构造函数的情况下实例化 class

ES6: Instantiate class without calling constructor

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

像这样:

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,并且想使用实体的构造函数来创建新对象,但不想在实例化已经持久化的对象(那些已经存在的对象)的实体时调用它们存储在数据库中)。

我知道学说 (PHP ORM) 使用这种方法,但据我所知他们正在使用代理 classes 来实现它。有什么简单的方法可以在打字稿中实现这一点(或通常在 ES6/ES7 中)?

我已经找到了这个问题ES6: call class constructor without new keyword, that asks for the opposite, and saw one answer mentioning Proxy对象。这听起来像是一种可行的方法,但从文档中我不确定它是否可以实现。

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

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