Parent constructor call overridden functions befor

2019-01-24 11:14发布

问题:

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 behavior. I simplify my real architecture but suppose I need to run render and some another routine and I put this calls in basic Bot class.

class Bot{
  constructor(){
    render();
  }
  render(){}
}

Each bot then override it's render function and can have some settings in constructor:

class DevilBot extends Bot{
  constructor(){
    super();
    this.color = 0xB4D333;
  }
  render(){
    createSomeMesh(this.color);
  }
}

The problem here is that before I call super() - this does not exist. But super (parent constructor) will call the overridden render that would need the color variable defined in the child constructor. I can suppose in the parent constructor that the child object would implement some init function with all needed settings and call it:

class Bot{
  constructor(){
    if (this.init) this.init();
    render();
  }
  render(){}
}

class DevilBot extends Bot{
  init(){
    this.color = 0xB4D333;
  }
  render(){
    createSomeMesh(this.color);
  }
}

But how good this approach and what is a preferred way to solve such a problem?

回答1:

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