【发布时间】:2021-03-09 03:29:08
【问题描述】:
我试图了解 Javascript 中原型继承和经典继承之间的区别。我遇到了一些声称The abstraction level for prototypal inheritance is never deeper than 1 的文章,但我不明白为什么。这是因为最后继承的原型可以访问其所有祖先的方法或属性,而经典继承只能访问其最后一个祖先?
从所有祖先访问方法的示例:
显示继承的简单图表:
Human ---> Zombie ---> ZombieBoss
代码
function Human(name, hp){
this.name = name
this.hp = hp
}
Human.prototype = {
sleep: function (){
this.hp += 50
console.log('human recovered')
},
constructor: Human
}
function Zombie(name, hp){
Human.call(this, name, hp)
}
Zombie.prototype = {
...Human.prototype,
sleep: function (){
this.hp += 100
console.log('zombie recovered')
Human.prototype.sleep.call(this)
},
constructor: Zombie
}
function ZombieBoss(name, hp){
Zombie.call(this, name, hp)
}
ZombieBoss.prototype = {
...Zombie.prototype,
sleep: function (){
this.hp += 500
console.log('zombie boss recovered')
Human.prototype.sleep.call(this) //Method from ancestor's ancestor can be accessed as well. Which is not possible with super()
Zombie.prototype.sleep.call(this) //Method from last ancestor
},
constructor: ZombieBoss
}
const king = new ZombieBoss('king', 1000)
king.sleep() //hp should be 1700
如果这不是唯一的原因,那么剩下的原因是什么?如果有一些简单的例子就好了。
【问题讨论】:
标签: javascript