0
function Fruit() {
    this.type = "fruit";
}

function Bannana() {
    this.color = "yellow";
    Fruit.call( this );
}

// instantiation
var myBanana = new Bannana();

// modifying type property    
Bannana.prototype.type = 'flower';

console.log( myBanana.type );

Output: fruit why is it not flower?

Robert
  • 10,126
  • 19
  • 78
  • 130

3 Answers3

2

Because myBanana has its own type property which shadows the one on the prototype.

enter image description here

When you are accessing a property, it is first looked up on the object itself. Only if it doesn't exist, it is looked up on its prototype, the prototype's prototype, etc until it is found.

If it is not found, undefined will be returned.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Ok. What if I want to change the `type` to `flower`. How can I do this? – Robert Jun 23 '15 at 00:44
  • 1
    Just like you do with any other property `myBanana.type = 'flower';` If you want that every `Banana` instance **shares** the same `type` property (instead of having their own) then you have to set it on the prototype, not in the constructor. I.e. remove `this.type = '...';` and add `Fruit.prototype.type = '...';` or `Banana.prototype.type = '...';`. – Felix Kling Jun 23 '15 at 00:45
  • Ok thanks! Explanation is clear. Is there an MDN article I can read up on with regards to looking up stuff and working up the prototype chain? – Robert Jun 23 '15 at 00:47
  • Have a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model – Felix Kling Jun 23 '15 at 00:48
1

Fruit.call(this); invokes Fruit with the new Bannana object as the this context, thus settings those properties directly on the object.

You can see this behaviour clearly by invoking the same pattern on an object literal.

var banana = {};

Fruit.call(banana);

console.log(banana.type); // 'fruit'
Oka
  • 23,367
  • 6
  • 42
  • 53
1

Because the call to Fruit.call( this ); in the Bannana constructor set the object property type to fruit (i.e. it was set in the object myBanana in your code).

It would only fall back to a property in the prototype if the property type were not present in the object myBanana.

Try appending the following to your code and you'll see that flower will be the output:

delete myBanana.type
console.log(myBanana.type);

This happens because the myBanana object won't have the type property itself anymore, so the look up for the type property will walk up the prototype chain.

Check this answer to see how this mechanism works in more detail:

https://stackoverflow.com/a/572996/689788

Community
  • 1
  • 1
A. Andres
  • 489
  • 4
  • 10