My English is not good, but I will try my best to explain my question simply. Description: Alert result is 1, I don't why, I think this should be 2015 to alert.
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);
Getters/setters can be used as wrappers over “real” property values to gain more control over operations with them. For instance, if we want to forbid too short names for user , we can have a setter name and keep the value in a separate property _name : let user = { get name() { return this.
Do you need getter and setters ? No.
The get syntax binds an object property to a function that will be called when that property is looked up.
You need to add writable: true like this
_year: {
value: 1,
writable: true
},
for __year_.
From Mozilla Developer Network:
writable
true if and only if the value associated with the property may be changed with an assignment operator. Defaults to false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With