prototype inheritance and the prototype object, why isn't used to this extent?

39 views Asked by At

I did a quick search but can't seem to find the answer to this question, just things referring to copying function prototypes when inheriting. Why not add properties to the constructor functions prototype obj, instead of using the this keyword. I'm sure there is a reason not to, but I'm trying to understand the nuances of javascript better. for example in normal prototype inheritance you would "this".

 function Dog(name,age,breed){
         this.name=name;
         this.age=age;
         this.breed=breed;
 }
 Dog.prototype.bark=function(){console.log("bark bark bark");}

 let spike=new Dog("Spike",6,"lab");
 let rover=new Dog("Rover",8,"poodle");


 //^with the constructor function, no instance has the bark function but
 //but refers to the same function on the constructor prototype obj, so the 
 //same function isn't being duplicated. However new keyword changes the 
 //context of this to refer to the obj so these properties are duplicated
 //on every instance.

 //I'm curious as to the reason why new doesn't change this to refer to the 
 //prototype obj for example and then have the instance refers its
 //constructor's prototype like with the bark function?

//for example why isn't this a common pattern and what are the reasons I 
//should use it.


function Dog(name,age,breed){
       Dog.prototype.name=name;
       Dog.prototype.age=age;
       Dog.prototype.breed=breed;
}

let spike=new Dog("Spike",6,"lab");
let rover=new Dog("rover",8,"poodle");


//I feel like the above code would be more DRY, I'm sure there is a reason
// this isn't common and I'm curious as to why
1

There are 1 answers

0
Supradeep On BEST ANSWER

When you have properties on the prototype, you are overriding the properties with new values each time you instantiate the Class i.e in your example, from the two statements below :

let spike=new Dog("Spike",6,"lab");

let rover=new Dog("rover",8,"poodle");

Here, according to your expectation, spike.name should be Spike and rover.name should be rover, but if you execute this code and check, both of them are rover.

The properties of spike are overridden by the properties of rover when you created the new instance rover. Each time, you create a new instance, the properties are overridden, the reason for this is methods or properties attached to the prototype are created only once and are inherited to their sub classes every time a new instance is created.

The reason we create a Constructor function and new instances from it is because we have different properties for each instance like Spike and rover. In case of methods, methods are generic to a Constructor which can be reused for all the instances which need not be created every time a new instance is created, hence, we attach them to the prototype instead of defining it with this keyword in the Constructor.