dima dima - 1 year ago 63
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download