简体   繁体   English

如何使用ES5扩展ES6类?

[英]How do I extend an ES6 class with ES5?

The reasons for doing this are complicated, but it boils down to flow not understanding mixins or any other way of modifying an ES6 class's prototype. 这样做的原因很复杂,但归结为流不理解mixins或任何其他修改ES6类原型的方法。 So I'm falling back to ES5, but I can't figure out how to call the constructor of an ES6 class without new : 所以我回到了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);

Answering this myself: 自己回答:

class A {
  constructor() {}
}

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

Not sure if there are any side-effects here or not 不确定这里是否有任何副作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM