4

Trying to understand prototypes. I'm playing around in Chrome's console and was hoping someone can point me to why this is happening.

function Gadget(name, color) {
     this.name = name;
     this.color = color;
     this.whatAreYou = function(){
       return 'I am a ' + this.color + ' ' + this.name;
     }
}

Gadget.prototype.price = 100;
Gadget.prototype.rating = 3;
Gadget.prototype.getInfo = function() {
    return 'Rating: ' + this.rating + ', price: ' + this.price;
};

var newtoy = new Gadget('webcam', 'black');

newtoy.constructor.prototype

Gadget {price: 100, rating: 3, getInfo: function} //Expected

Now if I try the following, prototype does not have the expected results.

function Gadget(name, color) {
     this.name = name;
     this.color = color;
     this.whatAreYou = function(){
       return 'I am a ' + this.color + ' ' + this.name;
     }
}

Gadget.prototype = {
     price: 100,
     rating: 3,
     getInfo: function() {
       return 'Rating: ' + this.rating + ', price: ' + this.price;
     }
};

var newtoy = new Gadget('webcam', 'black');

newtoy.constructor.prototype

Object {} //Empty Object!!!!!???
KingKongFrog
  • 13,946
  • 21
  • 75
  • 124

2 Answers2

4

jsFiddle Demo

This is because you overwrote the prototype instead of extending it when you did this:

Gadget.prototype = 

It is common when overwriting it, to make a facade of the constructor like this:

Gadget.prototype = {
 constructor : Gadget
}

So for your exact situation:

Gadget.prototype = {
 constructor : Gadget,
 price: 100,
 rating: 3,
 getInfo: function() {
   return 'Rating: ' + this.rating + ', price: ' + this.price;
 }
};
Travis J
  • 81,153
  • 41
  • 202
  • 273
  • That is the problem, but it would be more helpful if you explained how to do it properly. I will upvote it if you do – markasoftware Mar 29 '13 at 02:23
  • 1
    Ah...that actually makes sense. I'm reading the book Object-Oriented Javascript by Stoyan Stefanov and he does this but fails to mention clearly the repercussions, or I failed to realize. – KingKongFrog Mar 29 '13 at 02:25
1

Prototype is initially a special typed object. When you assign the prototype with a new object (the curly braces are short hand for a new object) you lose the special prototype object.

See How does JavaScript .prototype work? for a deeper explanation.

Community
  • 1
  • 1
Daniel Williams
  • 8,673
  • 4
  • 36
  • 47