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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…