The parent constructor calls overridden functions until all child constructors are complete

ECMAScript 6 (Harmony) introduces classes with the ability to inherit from one another. Suppose I have a game and some base class to describe the basic things for bot behavior. I simplify my real architecture, but suppose I need to run render and some other procedure, and I put these calls in the base class Bot .

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

Each bot then overrides its render and may have some settings in the 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 (the parent constructor) will call an overridden render , which will require the color variable defined in the child constructor. I can assume that in the parent constructor, the child object implements some init function with all the necessary settings and calls 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 is this approach and what is the preferred way to solve such a problem?

+7
javascript javascript-objects ecmascript-6
source share
1 answer

The following code will do what you want, although it is only supported in FF 41+ and Chrome 47+ (see https://kangax.imtqy.com/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 
+5
source share

All Articles