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?