2

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
John Winston
  • 1,260
  • 15
  • 30
  • 3
    "*I know I can achieve this easily with object concatenation*" Is there something that's missing in the question because `RobotMan.prototype = Object.assign({}, Human.prototype, Robot.prototype)` seems correct for your use case? – VLAZ Mar 04 '21 at 07:21
  • 1
    Does this answer your question? [Multiple inheritance/prototypes in JavaScript](https://stackoverflow.com/questions/9163341/multiple-inheritance-prototypes-in-javascript) – Ali Ataf Mar 04 '21 at 07:21
  • @VLAZ I tried that put somehow it didn't work previously, but it worked now. I think I have made and mistake somewhere in my code. Thank you for the help! – John Winston Mar 04 '21 at 07:28

1 Answers1

0

You can use assign method. This method is used to copy own enumerable property from one or more sources to an object.

The assign method returns the new object and I've assigned that object as RobotMan prototype.

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}`);
};

function RobotMan(name, hp, fuel) {
  Human.call(this, name, hp);
  Robot.call(this, name, fuel);
}

RobotMan.prototype = Object.assign({}, Human.prototype, Robot.prototype);
const robotMan = new RobotMan("robotman", 50, 40);
robotMan.eat();
robotMan.refuel();
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • I just realize that this is not the correct answer. Doing so will only copy and take a snapshot of the `Human.prototype` and `Robot.prototype` when `Object.assign` is called. If I mutate `Robot.prototype` after `Object.assign()`, `RobotMan.prototype` will not be changed. – John Winston Mar 11 '21 at 08:07