Js Prototype inheritance, is Object.create necessary?

42 Views Asked by At
function Animal(name) {
  this.name = name;
}

Animal.prototype.printName = function() {
    console.log(`my name is ${this.name}`)
}

function Dog(name) {
    Animal.call(this, name);
    this.speak = () => console.log('woof');
}

Dog.prototype = Animal.prototype // <=== **this line here**
Dog.prototype.constructor = Dog


const leo = new Dog('leo')
leo.speak()
leo.printName()

Is there any difference between Dog.prototype = Animal.prototype AND Dog.prototype = Object.create(Animal.prototype) or they are both same?

1

There are 1 best solutions below

0
Alexander Nenashev On

You can use more explicit Object.setPrototypeOf() to control prototype inheritance.
In that case you can add any methods to the Dog's prototype independently (even before inheritance).
So there's no need to rewrite the Dog's prototype.
Also you don't need to assign the Dog's constructor in that case, since it's kept intact.

function Animal(name) {
  this.name = name;
}

Animal.prototype.printName = function() {
    console.log(`my name is ${this.name}`)
}

function Dog(name) {
    Animal.call(this, name);
}

Dog.prototype.speak = () => console.log('woof');

Object.setPrototypeOf(Dog.prototype, Animal.prototype); 
// Dog.prototype.constructor = Dog - you don't need this, it's kept intact

const leo = new Dog('leo')
leo.speak()
leo.printName()