Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Class multiple inheritance through mixins

I'm trying to understand ES6 multiple inheritance using mixins.

I was following this article (simple mixins). But when I run the code, my output is:

  1. main
  2. Uncaught ReferenceError: this is not defined,
    and the error is pointing to console.log('main') again

I’m running it on the latest version of Chrome. Here is my code:

const RaceDayService = superclass => class extends superclass { 
    constructor(){
        console.log('service');
    }
}

const RaceDayDB = superclass => class extends superclass { 
    constructor(){
        console.log('db');
    }
}

class RaceDayUI {
    constructor(){
        console.log('ui');
    }
}

class RaceDay extends RaceDayDB(RaceDayService(RaceDayUI)){
    constructor(options){
        console.log('main');
    }
}

const raceDay = new RaceDay();

Any ideas on what I’m doing incorrectly?

Thanks!

like image 559
adviner Avatar asked Feb 04 '23 05:02

adviner


1 Answers

If your superclass contains a constructor, you have to call the super() method in the child's constructor:

const RaceDayService = superclass => class extends superclass { 
    constructor(){
        super();
        console.log('service');
    }
}

const RaceDayDB = superclass => class extends superclass { 
    constructor(){
        super();
        console.log('db');
    }
}

class RaceDayUI {
    constructor(){
        console.log('ui');
    }
}

class RaceDay extends RaceDayDB(RaceDayService(RaceDayUI)){
    constructor(options){
        super();
        console.log('main');
    }
}

const raceDay = new RaceDay();
like image 90
samanime Avatar answered Feb 06 '23 19:02

samanime