Reputation: 381
Below I am trying to define properties of an object using defineProperties function, but I am getting unexpected outcome when I print last line in this script. I expect 2005 to be logged at console, but I keep getting 2004. Same applies to other properties, like edition. Am I using this defineProperties function incorrectly?
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;
}
}
}
});
console.log(book);
console.log(book.year);
book.year = 2005;
console.log(book);
console.log(book.year);
Upvotes: 0
Views: 33
Reputation: 944538
You defined _year
as read only, so this._year = newValue
fails (silently). You need to make it writable.
_year: {
value: 2004,
writable: true
},
Upvotes: 2