父构造函数在所有子构造函数完成之前调用覆盖函数 [英] Parent constructor call overridden functions before all child constructors are finished
问题描述
ECMAScript 6(Harmony)引入了类
,可以从另一个继承。假设我有一个游戏和一些基本类来描述机器人行为的基本内容。我简化了我的真实体系结构,但假设我需要运行 render
和其他一些例程,我把这些调用放在基本 Bot
中类。
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);
}
}
这里的问题是在我打电话给<$ c之前$ c> super() - 此
不存在。但是 super
(父构造函数)将调用需要颜色的重写
render
code>在子构造函数中定义的变量。我可以在父构造函数中假设子对象将实现一些带有所有必需设置的 init
函数并调用它:
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?
推荐答案
以下代码可以满足您的需求,但目前仅支持FF 41+和Chrome 47+(请参阅 https://kangax.github.io/compat-table/es6/ )
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
这篇关于父构造函数在所有子构造函数完成之前调用覆盖函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!