Wednesday, 15 March 2017

prototypical inheritance in javascript

I am new to the world of Node/Javascript. I have gone through a lot of blogs how inheritance works in javascript, but still I have some confusion.

Here is the example that i setup.

var Mammal = function() {
  this.prop1 = "test1";
}

Mammal.prototype.greet = function(){
  console.log("Hello Word "+ this.prop1);
}


var Animal = function(){
  Mammal.call(this);
  this.prop2 = "test2";
}

Animal.prototype = Mammal.prototype;
//Animal.prototype = Object.create(Mammal.prototype);

var a = new Animal();
a.greet();

I am not sure between

Animal.prototype = Mammal.prototype; and

Animal.prototype = Object.create(Mammal.prototype);

What is the right way to setup inheritance ? Both works the similar way. Any one please help me to understand whats the difference between both.



via Deepak Kumar Padhy

No comments:

Post a Comment