TS / ES6:实例化类而不调用构造函数

Mar*_*mek 1 javascript node.js typescript ecmascript-6 es6-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
Run Code Online (Sandbox Code Playgroud)

我正在尝试开发TS mongo ORM,并希望使用实体的构造函数来创建新对象,但是当实例化已持久化对象(已经存储在DB中的那些对象)的实体时,不想调用它们。

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

我已经发现了这个问题ES6:不带new关键字的类构造函数,它要求相反,并看到一个提及Proxy对象的答案。听起来这是一种可行的方法,但是从文档中我不确定它是否可以实现。

ZER*_*ER0 7

您可以添加一个staticcreate方法,该方法从类原型创建一个Object。这样的事情应该起作用:

class Test {
  constructor(foo) {
    this.foo = 'test';
  }
  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, a instanceof Test); // undefined, true
Run Code Online (Sandbox Code Playgroud)