试图理解原型。我在 Chrome 的控制台中玩耍,希望有人能指出为什么会发生这种情况。
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
现在,如果我尝试以下操作,原型没有预期的结果。
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!!!!!???