How to use setter and getter in javascript, I met an error

My English is not very good, but I will try to explain my question as simply as possible. Description: Alert result 1, I do not understand, I think it should be 2015 to warn.

var book = {}; Object.defineProperties(book, { _year: { value: 1 }, edition: { value: 23 }, year: { get: function () { return this._year; }, set: function (newValue) { if (newValue > 2004) this._year = newValue; } } } ); book.year = 2015; alert(book.year); 
+7
javascript
source share
1 answer

You need to add an entry: true, like this

 _year: { value: 1, writable: true }, 

for __year _.

From the Mozilla Developer Network :

recordable

true if and only if the value associated with the property can be changed using the assignment operator. The default is false .

+10
source share

All Articles