This question already has an answer here:
Is it possible to inherit old-style class from ECMAScript 6 class in JavaScript?

(1个答案)


12天前关闭。




这样做的原因很复杂,但是可以归结为不了解mixin或修改ES6类原型(prototype)的任何其他方式。所以我回到了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);

最佳答案

我自己回答:

class A {
  constructor() {}
}

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

不知道这里是否有任何副作用

关于javascript - 如何使用ES5扩展ES6类?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50928070/

10-12 12:29
查看更多