Hello I found some difficulties when implementing javascript Object.defineProperties:
var book1 = {};
Object.defineProperties(book1, {
_year: {
value: 2004
},
edition: {
value: 1
},
year: {
get : function() {
return this._year;
},
set : function(newValue) {
if ((newValue - this._year) > 0) {
this.edition += 1;
} else if ((newValue - this._year) < 0) {
this.edition -= 1;
}
this._year = newValue;
}
}
});
book1.year = 2005;
document.write(book1.edition); //get 1, expect 2
document.write('<br/>');
book1.year = 2006;
document.write(book1.edition); //get 1, expect 3
document.write('<br/>');
Browser: Chrome 17.0.963.56
Any answer is welcome.
Thank you.
You have to specify
writable: trueas a property descriptor of_year. By default, it’s not writable, and assigning a value to a non-writable property doesn’t have any effect.I strongly recommend to activate the strict mode, because you will receive an error message when the assignment of a value to a read-only property fails.