如何使用ES5扩展ES6类? [英] How do I extend an ES6 class with ES5?

查看:60
本文介绍了如何使用ES5扩展ES6类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行此操作的原因很复杂,但是归结为无法理解mixin或其他任何修改ES6类原型的方法.所以我回到了ES5,但是我不知道如何在没有 new 的情况下调用ES6类的构造函数:

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. So I'm falling back to ES5, but I can't figure out how to call the constructor of an ES6 class without new:

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);

不确定这里是否有副作用

Not sure if there are any side-effects here or not

这篇关于如何使用ES5扩展ES6类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆