代码之家  ›  专栏  ›  技术社区  ›  Martin Adámek

ts/es6:实例化类而不调用构造函数

  •  1
  • Martin Adámek  · 技术社区  · 7 年前

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

    像这样的:

    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中的对象)的实体时调用它们。

    我知道Doctrine(PHORM)使用这种方法,但是他们使用代理类来实现它。在typescript中(或者通常在es6/es7中)有什么简单的方法可以实现这一点吗?

    我已经找到这个问题了 ES6: call class constructor without new keyword ,要求相反,看到一个回答提到 Proxy 对象。这听起来是一个可行的方法,但从文件我不确定是否可以实现。

    1 回复  |  直到 7 年前
        1
  •  6
  •   ZER0    7 年前

    您可以添加 static 方法create,从类原型创建对象。类似的事情应该管用:

    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