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
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 :Here, according to your expectation,
spike.name
should beSpike
androver.name
should berover
, but if you execute this code and check, both of them arerover
.The properties of
spike
are overridden by the properties ofrover
when you created the new instancerover
. Each time, you create a new instance, the properties are overridden, the reason for this ismethods
orproperties
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
androver
. 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 theprototype
instead of defining it withthis
keyword in the Constructor.