Definition. To define attributes, you need to use the corresponding function, such as:
Object.defineProperty(obj, "prop", propDesc)
If obj does not have its own attribute prop, the function of this function is to add its own attribute prop to obj and assign a value,
The parameter propDesc specifies the characteristics of the attribute (writability, enumerability, etc.).
If obj already has its own attribute prop, the function of this function is to modify the characteristics of the existing attribute, including its attribute value.
1. defineProperty
var book = { _year: 2004, edition: 1 }; Object.defineProperty(book, "year", { get: function(){ return this._year; }, set: function(newValue){ if (newValue > 2004) { this._year = newValue; this.edition += newValue - 2004; } } }); book.year = 2005; alert(book.edition); //2
2. __defineSetter__ and __defineGetter__
var book = { _year: 2004, edition: 1 }; //legacy accessor support book.__defineGetter__("year", function(){ return this._year; }); book.__defineSetter__("year", function(newValue){ if (newValue > 2004) { this._year = newValue; this.edition += newValue - 2004; } }); book.year = 2005; alert(book.edition); //2
The above is today’s summary of JavaScript learning, and it will continue to be updated every day. I hope you will continue to pay attention.