Reputation: 910
Trying to clear up some prototypal inheritances basics.
function thirdSampleObject(){
this.first_var = 3;
this.update = function(){"Hi I am a function"};
}
var thirdClass = new thirdSampleObject();
var fourthClass = new thirdSampleObject();
thirdClass.first_var = 5;
fourthClass.first_var = 7;
console.log(thirdClass.first_var); //returns 5
console.log(fourthClass.first_var); //returns 7
thirdSampleObject.prototype.first_var = 10;
console.log(thirdClass.first_var); //returns 5 "protectected" within it's own instance of the object
console.log(fourthClass.first_var); //returns 7 "protectected" within it's own instance of the object
var fithClass = new thirdSampleObject();
console.log(fithClass.first_var); //returns 3 ? Wouldn't this return 10 at this point?`
I would expect console.log(fithClass.first_var)
to return 10 since I overwrote the value in the prototype. However, returns the number set in "original" prototype definition. Trying to wrap my head around why.
Upvotes: 1
Views: 44
Reputation: 628
Prototype inheritance will happen if the object doesn't have the property and the prototype of that object have the property.
function thirdSampleObject(){
this.first_var = 3;
this.update = function(){"Hi I am a function"};
}
thirdSampleObject.prototype.first_var = 10;
var fifthClass = new thirdSampleObject();
fifthClass.hasOwnProperty('first_var'); // returns true. i,e fifthClass object have its own property 'first_var'.
console.log(fifthClass.first_var);
delete fifthClass.first_var //here we are deleting the property from object.
fifthClass.hasOwnProperty('first_var'); // returns false
console.log(fifthClass.first_var); // returns 10
Upvotes: 1
Reputation: 413717
Regardless of the value of first_var
on the prototype, your constructor explicitly sets the value on the newly created object.
The code in the constructor is doing exactly the same thing as those assignments in your code outside the constructor, in other words. Code in the constructor function is just code, and in the constructor this
refers to the new object, not the prototype.
Upvotes: 4