Problem overwriting prototype with object in javascript

Trying to understand prototypes. I play in the Chrome console and hope someone can tell me 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, the prototype will 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!!!!!??? 
+4
source share
2 answers

jsFiddle Demo

This is because you overwritten the prototype, rather than expanding it when you did:

 Gadget.prototype = 

Usually, when he rewrites it to make the facade of the constructor as follows:

 Gadget.prototype = { constructor : Gadget } 

So, for your specific situation:

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

The prototype is initially a special typed object. When you assign a prototype to a new object (braces are a short hand for a new object), you lose a special prototype of the object.

See How JavaScript.prototype Works? for a deeper explanation.

+1
source

All Articles