1

I came across below mentioned ways to achieve prototypal inheritance in javascript.

Way 1:

Dog.prototype = Object.create(new Animal());

Way 2:

Dog.prototype = new Animal();

Way 3:

Dog.prototype = Animal.prototype;

I tried creating a simple demo for it all of them are giving exactly similar end result.

Below is the snippet

function Animal(name) {
    this.name = name;
}
Animal.prototype.sleep = function() {
    console.log(this.name + ': Zzz...');
}
function Dog(name) {
    this.name = name;
}
// Create a reference for the prototype Way 1
Dog.prototype = Object.create(new Animal());

// Create a reference for the prototype Way 2
Dog.prototype = new Animal();

// Create a reference for the prototype Way 3
Dog.prototype = Animal.prototype;
Dog.prototype.makeSound = function() {
    console.log(this.name + ': Woof woof!');
}
Dog.prototype.sleep = function() {
    console.log(this.name + ': Overriding Zzzz....');
}
var dog = new Dog('Lassie');
dog.makeSound(); // Lassie: Woof woof!
dog.sleep(); // Lassie: Overriding Zzzz....

if someone could help me with this; wanted to know if there is any strategical difference between all of these? What are the programmatical nuances of all these different ways?

The VOYOU
  • 522
  • 4
  • 14
  • Actually, all of them are wrong. It should be `Dog.prototype = Object.create(Animal.prototype)`. Also you might want to do `Animal.call(this, name)` instead of `this.name = name` in the `Dog` constructor. – Bergi Apr 21 '19 at 18:45
  • @Bergi I can add one more way i.e. Way 4; the question itself is about that WRONG itself that you are talking about. would be please mind telling exactly what's wrong with all of those. – The VOYOU Apr 21 '19 at 18:48
  • `dog instanceof Animal` will work in all three cases. The differences will show up if you follow the prototype chain of `dog` - it will have three different lengths. Try inspecting it in the devtools, or accessing it with `Object.getPrototypeOf(…)`. – Bergi Apr 21 '19 at 18:48
  • @Bergi just curious is there any tag available in SO that can mark this question "Partial Duplicate" because of the question you tagged here just having the partial information about the problem. – The VOYOU Apr 21 '19 at 18:51
  • You can [edit] the question to remove the parts that were answered by the duplicate, and more explicitly ask about the parts that are still unclear. – Bergi Apr 21 '19 at 18:52
  • Maybe also have a look at [this](https://stackoverflow.com/questions/11088365/why-wouldnt-i-use-child-prototype-parent-prototype-rather-than-child-prototype-new-parent) and [that](https://stackoverflow.com/questions/12592913/what-is-the-reason-to-use-the-new-keyword-here) – Bergi Apr 21 '19 at 18:52
  • thanks @Bergi I'll check on those links as well :) – The VOYOU Apr 21 '19 at 18:55

0 Answers0