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!!!!!???
2
  • Are you looking for newtoy.__proto__? ie what are you seeking going through newtoy.constructor? Commented Mar 29, 2013 at 2:22
  • stackoverflow.com/a/8096017/783743 Commented Mar 29, 2013 at 2:38

2 Answers 2

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;
 }
};
Sign up to request clarification or add additional context in comments.

2 Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.