Issue with overwriting prototype with object in javascript
constructor, javascript, prototype
Solution
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;
}
};
Problem
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!!!!!??? ```