I am trying to understand the difference between Prototypal Inheritance and Classical Inheritance in Javascript. I came across some articles claiming The abstraction level for prototypal inheritance is never deeper than 1, but I don't understand why. Is that because the last inherited prototype has access to methods or properties of all its ancestors, whereas classical inheritance only has access to its last ancestor?
An example of accessing methods from all ancestors:
Simple graph to show inheritance:
Human ---> Zombie ---> ZombieBoss
Code
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
If this is not the only reason, what are the remaining reasons for that? It would be great if there are some simple examples.