【问题标题】:How do I extend an ES6 class with ES5? [duplicate]如何使用 ES5 扩展 ES6 类? [复制]
【发布时间】:2018-11-28 09:32:45
【问题描述】:

这样做的原因很复杂,但归结为不理解 mixins 或任何其他修改 ES6 类原型的方式。所以我回退到 ES5,但我不知道如何在没有new 的情况下调用 ES6 类的构造函数:

class A {
  constructor() {}
}

function B() {
  // what do I put here?  I would do something like
  // A.prototype.constructor.call(this) but that throws an error saying the
  // constructor can only be called with `new`
}
B.prototype = Object.create(A.prototype);

【问题讨论】:

  • 您是否有特定原因要避免使用new?我认为调用new 是唯一(并且是正确)的方法

标签: javascript ecmascript-6 ecmascript-5


【解决方案1】:

我自己回答这个问题:

class A {
  constructor() {}
}

function B() {
  Object.assign(this, new A());
}
B.prototype = Object.create(A.prototype);

不确定这里是否有任何副作用

【讨论】:

  • 我以为你想在没有new的情况下调用构造函数?
  • 无论如何,根据我对本规范ecma-international.org/ecma-262/6.0/…的理解,我们很可能绝不可以跳过关键字new
  • 我只是想让 B 扩展 A,ES5 的做法是在 B 内部执行 A.call(this),如果我的问题中的措辞暗示了不同的意图,对不起
猜你喜欢
  • 1970-01-01
  • 2019-11-18
  • 2018-06-29
  • 1970-01-01
  • 2016-08-20
  • 2016-01-03
  • 2010-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多