javascript - 如何在 ES6 中调用类的父类的父类的构造函数?

标签 javascript ecmascript-6

我正在使用 ES6 类,我的类 (A) 扩展了类 B,类 B 扩展了类 C。A 如何扩展方法,然后调用 C 的该方法版本。

class C {
  constructor() {
    console.log('class c');
  }
}

class B extends C {
  constructor() {
    super()
    console.log('no, I don't want this constructor.');
  }
}

class A extends B {
  constructor() {
    // What should I be doing here?  I want to call C's constructor.
    super.super();
  }
}

编辑:谢谢大家,我将停止尝试做这种愚蠢的事情。在我的情况下,代码重用的微小收获不值得花功夫。

最佳答案

You can’t not call the parent’s constructor in an ES6 class.根据您的评论判断,也许您应该尝试这样的事情?

class Mixin {
  static include(constructor) {
    const descriptors = Object.getOwnPropertyDescriptors(Mixin.prototype);

    Object.keys(descriptors).forEach(name => {
      Object.defineProperty(constructor.prototype, name, descriptors[name]);
    });
  }

  someCommonFunction() {
    // Perform operation common to B and C
  }
}

delete Mixin.prototype.constructor;

class B extends A {
}

Mixin.include(B);

class C extends A {
}

Mixin.include(C);

关于javascript - 如何在 ES6 中调用类的父类的父类的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42861855/

相关文章:

javascript - 无法使用 jQuery 触发 Knockout 数据绑定(bind)

java - 根据时间从mysql中删除记录

javascript - 我该如何解决这个不断扩大的问题?

javascript - 在没有包装器的情况下将新对象添加到另一个对象

javascript - 如何在react.JS中将子窗口url获取到父窗口中?

javascript - 当我们向子节点添加更多节点时,Vis.js 网络树结构困惑

javascript - leaflet.js 在鼠标悬停在单独的列表上时突出显示 GeoJSON

javascript - Express 应用程序中未加载静态 Javascript 文件

javascript - 为什么 ES6 IIFE 和 ES5 IIFE 的执行上下文不同?

javascript - 我如何在 es6 中使用 module.exports.function?