嘗試理解原型。我在Chrome的控制檯中玩耍,並希望有人能指出我爲什麼會發生這種情況。用javascript中的對象覆蓋原型的問題
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!!!!!???
你在找'newtoy .__ proto__'嗎?即你在尋找什麼'newtoy.constructor'? –
http://stackoverflow.com/a/8096017/783743 –