Parent constructor call overridden functions before all child constructors are finished

后端 未结 1 639
温柔的废话
温柔的废话 2020-12-17 00:25

ECMAScript 6 (Harmony) introduces classes with ability to inherit one from another. Suppose I have a game and some basic class to describe basic things for bot

1条回答
  •  既然无缘
    2020-12-17 01:00

    The following code will do what you want, though it is currently only supported in FF 41+ and Chrome 47+ (see https://kangax.github.io/compat-table/es6/)

    class Bot{
        constructor(){
            if (new.target === Bot)
                this.render();
        }
        render(){
            console.log('Bot rendered');
        }
    }
    
    class DevilBot extends Bot{
        constructor(){
            super();
            this.color = 0xB4D333;
            this.render();
        }
        render(){
            console.log('DevilBot rendered with', this.color);
        }
    }
    
    var bot = new Bot();       // Bot rendered
    var dev = new DevilBot();  // DevilBot rendered with 11850547
    

    0 讨论(0)
提交回复
热议问题