Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

javascript - Parent constructor call overridden functions before all child constructors are finished

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...