2016-10-11 38 views
0

所以我已經知道在Javascript中我們可以使用defineProperties來定義對象的多個屬性。因此,我已經在下面的簡單代碼中嘗試了它,但我並不清楚得到我想要的結果。這似乎是訪問者不工作,我不知道爲什麼。JavaScript對象defineProperties不起作用

var book = {}; 
Object.defineProperties(book,{ 
_year: { 
    value: 2004 }, 
edition: { 
    value: 1}, 
year: { 
    get: function(){ 
    this._year;}, 
    set: function(value){ 
    if(value>2004){ 
    this._year = value; 
    this.edition = this.edition + value - 2004; 
}); 
this.year = 2016; 
alert(book.edition); //1 why?? 
+0

你似乎缺少一些'}' – j08691

+0

是的,我只是意識到我錯過了那些右括號,格式化風格並沒有說清楚。謝謝 – Celaro

回答

2

你有多個錯誤在你的代碼,但主要問題是,如果你定義一個value屬性則是默認只讀:

MDN: Object.defineProperty


true當且僅當與屬性相關聯的值可以通過賦值運算符進行更改。
默認爲false

您需要添加writable: true使這些屬性可寫的。

所以,你的代碼必須看起來像這樣(包括修正所有其他錯誤你有):

var book = {}; 
 
Object.defineProperties(book, { 
 
    _year: { 
 
    value: 2004, 
 
    writable: true // << writable 
 
    }, 
 
    edition: { 
 
    value: 1, 
 
    writable: true // << writable 
 
    }, 
 
    year: { 
 
    get: function() { 
 
     // << missing return 
 
     return this._year; 
 
    }, 
 
    set: function(value) { 
 

 
     if (value > 2004) { 
 
     this._year = value; 
 
     this.edition = this.edition + value - 2004; 
 
     } 
 
    } 
 
    } 
 
}); 
 
book.year = 2016; // << here you used this instead of book 
 
console.log(book.edition);

+0

非常感謝,確實我在使用defineProperties時只是閱讀了這個事實。默認情況下,可枚舉,可配置和可寫是錯誤的。 – Celaro

+0

getter中的'return'似乎並不需要 – j08691

+0

@ j08691它確實與給定的代碼無關,但如果OP嘗試在另一個地方讀取屬性'year',它將返回'undefined'代碼,所以我添加了這個更正作爲額外的信息。因爲否則這個吸氣劑沒有多大意義。 –