我正在尝试使用 mixins 来理解 ES6 多重继承。

我正在关注 this article (简单的 mixins)。但是当我运行代码时,我的输出是:

  • main
  • Uncaught ReferenceError: this is not defined ,
    并且错误再次指向 console.log('main')

  • 我在最新版本的 Chrome 上运行它。这是我的代码:

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

    关于我做错了什么的任何想法?

    谢谢!

    最佳答案

    如果父类(super class)包含构造函数,则必须在子类的构造函数中调用 super() 方法:

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

    关于javascript - ES6 类通过 mixins 进行多重继承,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44703071/

    10-12 16:25