2017-03-16 23 views
1

大家好,我最近讀了Professional.JavaScript.for.Web.Developers.3rd.Edition。這是我從中學到的代碼。但是,輸出與我讀的書不同。當我運行下面的代碼時,book.edition is 1,book._year是2004,book.year是2004.發生了什麼?我的代碼出了什麼問題?如何使用Object.defineProperties?

var book = {}; 

Object.defineProperties(book, { 
    _year: { 
    value: 2004 
    }, 
    edition: { 
    value: 1 
    }, 

    year: { 
    get: function() { 
     return this._year; 
    }, 

    set: function(newValue) { 
     if (newValue > 2004) { 
     this._year = newValue; 
     this.edition += newValue - 2004; 
     } 
    } 
    } 
}); 

book.year = 2005; 
console.log(book.edition); 
console.log(book._year); 
console.log(book.year); 
+0

什麼是預期的行爲? –

+0

這看起來像對我來說是正確的輸出。 'book._year'只是直接獲取變量,'book.year'是一個getter函數,它返回'_year',所以它們都應該返回相同的值 – Jayce444

+0

@ Jayce444,他們應該返回2005年而不是2004年,而'edition'應該是2。 –

回答

3

屬性_year和你的對象的edition應該被定義爲可寫。否則,在今年的制定者中重新定義它們是沒有用的。

var book = {}; 
 

 
Object.defineProperties(book, { 
 
    _year: { 
 
    value: 2004, 
 
    writable:true 
 
    }, 
 
    edition: { 
 
    value: 1, 
 
    writable:true 
 
    }, 
 

 
    year: { 
 
    
 
    get: function() { 
 
     return this._year; 
 
    }, 
 

 
    set: function(newValue) { 
 
     
 
     if (newValue > 2004) { 
 
     this._year = newValue; 
 
     this.edition += newValue - 2004; 
 
     } 
 
    } 
 
    } 
 
}); 
 

 

 
console.log(book.edition); 
 
console.log(book.year); 
 
book.year=2005; 
 
console.log(book.edition); 
 
console.log(book.year);