如何在ES6中调用班级的父级的父级构造函数? [英] How can I call my class' parent's parent's constructor in ES6?

查看:165
本文介绍了如何在ES6中调用班级的父级的父级构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using ES6 classes and my class (A) extends class B and class B extends class C. How can A extend a method and then call C's version of that method.

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

谢谢,我将停止尝试做这个愚蠢的事情.在我的情况下,代码重用的次要收获不值得杂技.

Thanks all, I'm going to stop trying to do this silly thing. The minor gains in code-re-use aren't worth the acrobatics in my situation.

推荐答案

您可以不要在ES6类中调用父级的构造函数.根据您的评论判断,也许您应该尝试这样的事情?

You can’t not call the parent’s constructor in an ES6 class. Judging by your comment, maybe you should try something like this?

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

这篇关于如何在ES6中调用班级的父级的父级构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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