在JS中我創建了一個對象。我想爲對象的原型添加一個新的屬性,並且屬性將會因實例而異。 現在加入我使用的價值得到。但它給了我錯誤。我已經添加了下面的代碼。是否可以將值添加到js中某個對象的新屬性?
我該如何做到這一點?
我已經用google搜索了這個。而我所瞭解的全部是得到他們增加價值到現有的財產。但是我想增加新的屬性的值,這將會改變實例。
var computer = function (name, ram) {
this.name = name;
this.ram = ram;
};
Object.defineProperty(computer.prototype, "graphic", {
set: function graphic(value) {
this.graphic = value;
},
get: function graphic() {
return this.graphic;
},
});
var vio = new computer("sony", "8gb");
vio.graphic = "gtx980";
console.log(vio.graphic);
錯誤按摩:
'但它給了我錯誤 - 我們應該猜測錯誤是什麼? –
您無法將屬性getter/setter設置爲自己的名稱。使用局部變量,這在原型方法上很煩人,或者設置'this._graphic'作爲'this.graphic'而不是 – dandavis
錯誤:''堆棧空間不足',顯然。 –