2017-03-09 85 views
0

在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);

錯誤按摩:

enter image description here

+0

'但它給了我錯誤 - 我們應該猜測錯誤是什麼? –

+0

您無法將屬性getter/setter設置爲自己的名稱。使用局部變量,這在原型方法上很煩人,或者設置'this._graphic'作爲'this.graphic'而不是 – dandavis

+0

錯誤:''堆棧空間不足',顯然。 –

回答

1

重讀你的問題,我會回答實際的擔憂:當你把東西放在原型

,它們在所有實例之間共享(就好像你將它們添加到經典中的類一樣像Java這樣的語言)。 當你把東西放在this上時,它們只能用於特定的實例。

下工作,沒有制定者或干將:

function Computer(name, ram) { // Please use Capital names for constructors 
    this.name = name; 
    this.ram = ram; 
}; 

let vio = new Computer('sony', '8gb'); 
vio.graphic = 'gtx980'; 

graphic屬性將只存在於vio舉行的實例,不是每個計算機實例在那裏。

如果,另一方面你要做到這一點:

function Computer(name, ram) { 
    this.name = name; 
    this.ram = ram; 
} 

Computer.prototype.graphic = 'gtx980'; 

// All instances of Computer will now have a .graphic with the value of 'gtx980'. 

你得到錯誤的原因是,你定義一個二傳手的graphic,在裏面,你想分配給graphic,其調用設置器graphic,該設置器嘗試分配給graphic,其調用....你明白了。

解決的方法是更改​​實際變量的名稱(例如_graphic)。

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);

注意JS確實沒有私有變量。您將無法阻止某人更改_graphic

+0

它的工作原理。謝謝。 – zoha131

+0

我可以知道它背後的理論嗎? 如果我打電話'console.log(Object.getOwnPropertyNames(vio));' 我得到_graphic而不是圖形作爲屬性。這是爲什麼? – zoha131

+0

因爲這是實際的屬性。 Getters和setter不是對象上的實際屬性,而是底層的'_graphic'。 –

相關問題