Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call my class' parent's parent's constructor in ES6?

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

Edit: 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.

like image 328
Julian Avatar asked Mar 17 '17 15:03

Julian


1 Answers

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);
like image 145
Ry- Avatar answered Oct 10 '22 00:10

Ry-