I want to make a prototype that inherits from two different prototypes. I know I can achieve this easily with object concatenation or create methods in the constructor function, but I want to have functions that would be saved in the prototype chain instead.
Let say I have Human
and Robot
, and I want to create a new type RobotMan
:
function Human(name, hp){
this.hp = hp || 100
this.name = name
}
Human.prototype.eat = function (){
this.hp += 50
console.log(`current hp: ${this.hp}`)
}
function Robot(name, fuel){
this.fuel = fuel || 100
this.name = name
}
Robot.prototype.refuel = function (){
this.fuel += 25
console.log(`current fuel: ${this.fuel}`)
}
How can I combine to prototype into one and make RobotMan
inherit from both Human
and Robot
?
function RobotMan(name, hp, fuel){
Human.call(this, name, hp)
Robot.call(this, name, fuel)
}
RobotMan.prototype = Object.create(Human.prototype) //? How should I write this line correctly?
RobotMan.prototype.constructor = RobotMan