如何 rerun/reuse class 构造函数

How to rerun/reuse class constructors

我最近从 es5 迁移到 es6 类 并且偶然发现了这个问题,我不能再调用没有 new 的构造函数了。

在我的特定情况下,我想避免对象创建和内存分配。这就是为什么我想重用旧对象(如果您可能会问,这是一个瓶颈)。

所以在 es5 中我这样做了:

// extend adds all given methods to the classes prototype
extend([myClass1, myClass2, ...], {
  fromArray (arr) {
      this.constructor(arr)
  }
})

这段代码会将数组传入知道如何处理它的构造函数。这使我能够 运行 高性能代码而无需创建大量对象。

好吧 - 这在 es6 中不再可能了。我认为可以解决这个问题的唯一方法是引入一个 init() 方法来完成构造函数的工作。但是,如您所见,我在许多 类 上都需要此功能。拥有 init() 功能感觉就像是添加功能的一种笨拙和臃肿的方式。 也不可能将现有函数用作可以重用的构造函数,因为这不是有效的语法:

class Foo {
    constructor: someReusableFunction // Syntax Error
}

我读到了有关撤回的 call constructor 的信息,它将解决很多用例和我的问题(所有 init 的东西都会进入调用构造函数)。他们说,这最好用装饰器来解决。但是我不确定装饰器将如何解决这个问题。

不允许调用构造函数的动机是,将来可能会使用现在已撤消的调用构造函数。那么有没有可能取消限制?

我的问题:

Having an init() function feels like a hacky and bloated way to add the functionality back.

你可以只写一个 class 在构建过程中调用 init:

 class Constructable {
   constructor(...args) {
     this.init(...args);
  }

  init(a, b, c) { /*...*/ }
}

然后扩展一下:

 class Test extends Constructable {
  init(a, b, c) { /*...*/ }
 }

以便构造函数也被继承,您可以将其用作:

 const test = new Test(1, 2, 3);
 test.init(4, 5, 6);

Its also not possible, to use an existing function as constructor which can be reused

其实是的,只需要添加一个调用函数的构造函数即可:

 constructor(...args) {
  someReusableFunction.call(this, ...args);
 }