This article mainly introduces the knowledge points of property definition methods in javascript, the basic usage methods of property definition methods, and various methods. If you are interested, refer
Definition ).Corresponding functions are required to define attributes, such:
Object. defineProperty (obj, "prop", propDesc)
If obj does not have the property prop, the function adds a property prop to obj and assigns a value,
The propDesc parameter specifies the attributes (such as writability and enumerability) of this attribute ).
If obj already has the property prop, the function is used to modify the property of this existing property, including its property 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 the summary of today's javascript learning, and will be updated every day. I hope you will continue to pay attention to it.