dima dima - 1 month ago 5x
Javascript Question

Property set in constructor overrides property on prototype

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
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.


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.