Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: property assignment through prototype

I'm struggling to understand the difference of the following 2 sets of code. The original code is from the famous Ninja tutorial and I have simplified a bit for myself.

Question: I think I understand how CodeA works. Ninja.prototype.swung = false is assigning a new property into function Ninja(), and ninjiaA.swung evaluates to false because of that. However, in CodeB, when we declare the function Ninja() with this.swung = true in the beginning, the later assignment of Ninja.prototype.swung = false does not take an effect, and ninjaA.swung remains to be evaluated to true. I'm failing to understand why this later assignment does not work in CodeB. Could somebody please enlighten me on this?

CodeA:

function Ninja(){}  
Ninja.prototype.swung = false; 
var ninjaA = new Ninja();
ninjaA.swung; //evaluates to false

CodeB:

function Ninja(){ 
  this.swung = true; 
}  
Ninja.prototype.swung = false; //I'm expecting this changes swung to false, 
                               //but it doesn't.
var ninjaA = new Ninja();      
ninjaA.swung; //evaluates to true

Thanks a lot in advance.

like image 420
c4il Avatar asked Jul 28 '10 00:07

c4il


2 Answers

When you declare a property using this inside the constructor function, it gets attached to every object of that constructor.

When you declare a property on the prototype of that constructor function, it remains there and all objects of that constructor refer to it. When you have a property with the same name in the object and in the prototype chain, the object's property hides the one on the prototype.

Think how the property is evaluated in the prototype chain which might makes things clearer.

CodeA:

ninjaA.swung

1. Is swung a property of the current object - No
2. Is swung a property of the current object's prototype - Yes
    2.1. Return it

CodeB:

ninjaA.swung

1. Is swung a property of the current object? - Yes
    1.1 Return it

In code B, it never gets to the property on the prototype.

like image 190
Anurag Avatar answered Sep 30 '22 18:09

Anurag


When calling Ninja as a constructor you assign the value true to swung. Before the constructor is executed the object will look like this:

{
    prototype : {
        swung : false
    }
}

After the constructor is executed:

{
    prototype : {
        swung : false
    },
    swung : true
}

When you ask for the property swung the prototype chain will be checked at each level to see if it exists. If it doesn't exist the value undefined will be returned.

like image 27
ChaosPandion Avatar answered Sep 30 '22 19:09

ChaosPandion