2017-03-16 3 views
1

皆、私は最近Professional.JavaScript.for.Web.Developers.3rd.Editionを読んでいます。ここで私はそれから学ぶコードです。しかし、出力は私が読んだ本とは異なります。以下のコードを実行すると、book.edition is 1book._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'は '_year'を返すゲッター関数ですので、両方とも同じ値を返すべきです – Jayce444

+0

@ Jayce444 2004年の代わりに2005年を返すべきです。 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);

関連する問題