Object.defineproperty ()
The Object.defineproperty () method defines a new property directly on an object, or modifies an existing property and returns the object.
Grammar
Object.defineProperty(obj, prop, descriptor)
Parameters
obj
The object that needs to define the property.
prop
The name of the property that needs to be defined or modified.
descriptor
The descriptor of the property that needs to be defined or modified.
Description
This method allows you to precisely add or modify the properties of an object. In general, we add a property to an object that is created by assignment and displayed in the property enumeration ( for...in
or Object.keys
method), but the value of the property added in this way can be changed, or it can be deleted. The Object.defineProperty()
default settings for these additional details are allowed to be changed by use. For example, by default, using an Object.defineProperty()
added property value is immutable.
There are two main forms of attribute descriptors present in an object:
Data descriptors and access descriptors
A data descriptor is an attribute that has a writable or non-writable value. An access descriptor is a property that is described by a pair of getter-setter function functions. Descriptors must be one of two forms;
Both the data descriptor and the access descriptor have the following optional key values:
configurable
: true
This property can be changed and deleted only if the property is configurable. Default isfalse
enumerable
: true
This property can appear in an enumeration property of an object only if the property is enumerable. Default isfalse
value
: The value that corresponds to the property. can be any valid JavaScript value (numeric, object, function, etc.). Default isundefined
writable
: true
This property can be changed only by the assignment operator only if the property's writable is. Default isfalse
get
: A method that provides a getter to a property, or if no getter is available undefined
. The method return value is used as the property value.undefined
set
: A method that provides a setter to a property, if there is no setter undefined
. The method will accept the unique parameter and assign the new value of the parameter to the property. The default is undefined
.
Using __proto__Object.defineproperty (obj,"Key", {__proto__:NullNo inherited property value:"Static"No enumerable.No configurable.No writable.as default});An explicitObject.defineproperty (obj,"Key", {enumerable:False, Configurable:False, writable:False, Value:"Static"});Looping through the same objectfunction withvalue (value) {var d = WITHVALUE.D | | (WITHVALUE.D = {enumerable: false, writable: false, Configurable: false, Value: null}); D.value = value; return D;} //... And... object.defineproperty (obj, "key", Withvalue (//if freeze is available, prevent code from adding or removing properties of object prototypes //(value, get, set, enumerable , writable, configurable) (object.freeze| | object) (object.prototype);
Creating properties
If the specified attribute does not exist in the object, Object.defineproperty () creates this property. When some fields are omitted from the descriptor, these fields will use their default values. The default value for a field that has a Boolean value is false. The default value for the Value,get and set fields is undefined. If there is no get/set/value/writable when defining a property, it is categorized as a data descriptor.
var o = {};Create a new objectExample of an object property added with DefineProperty and a data property descriptorObject.defineproperty (O,"A", {value:Panax Notoginseng, writable:True, Enumerable:True, configurable:true});Object O has property A with a value of 37Example of an object property added with DefineProperty with a accessor property descriptorvar BValue;Object.defineproperty (O,"B", {get:function(){return bValue; }, set:function (newvalue) {bValue = newvalue;}, Enumerable: true, Configurable: true}); o.b = 38;< Span class= "hljs-comment" >//object o has attribute B, a value of 38//the value of O.B is now all identical to Bvalu E, unless O.B is Redefined//data descriptor and access descriptor cannot be mixed using "conflict", {value: 0x9f91102, get: Span class= "hljs-function" >function () { return 0XDEADBEEF;}); //throws a Typeerror:value appears only in data descriptors, get appears @ Accessor des Criptors
modifying properties
If the property already exists, Object.defineproperty () will attempt to modify the property based on the value in the descriptor and the current configuration of the object. If the configurable attribute of the descriptor is false (that is, the attribute is non-configurable), other attributes cannot be modified except for writable, and the data and access descriptors cannot be switched to each other.
If the configurable of an attribute is false, its writable attribute can only be modified to false.
If you attempt to modify the Non-configurable property attribute (other than writable), a TypeError exception will be generated unless the current value is the same as the modified value.
Writable Property
When the attribute property attribute writable is set to false, the property cannot be modified, non-writable is represented. Modifying a non-writable property does not change the value of the property, nor does it report an exception.
var o = {}; // 创建一个新对象Object.defineProperty(o, "a", { value : 37, writable : false });console.log(o.a); // 打印 37o.a = 25; // 没有错误抛出(在严格模式下会抛出,即使之前已经有相同的值)console.log(o.a); // 打印 37, 赋值不起作用。
Enumerable characteristics
The property attribute enumerable defines whether an object's properties can be enumerated in for...in loops and Object.keys ().
var o = {};Object.defineproperty (O,"A", {value:1, Enumerable:true});Object.defineproperty (O,"B", {value:2, Enumerable:false}); object.defineproperty (o, "C", {value: 3}); //enumerable defaults to FALSEO.D = 4; //if you create a property of an object using a direct assignment, the enumerable of this property is Truefor (var i in o) {console.log (i);} //print ' a ' and ' d ' (in undefined order) object.keys (o); //["a", "D"]o.propertyisenumerable ( ' a '); //trueo.propertyisenumerable ( ' B '); //falseo.propertyisenumerable ( ' C '); //false
Configurable characteristics
The configurable attribute indicates whether an object's properties can be deleted, and whether other attributes other than the writable attribute can be modified.
var o = {};Object.defineproperty (O,"A", {get:function(){Return1;}, Configurable:False});Throws a TypeErrorObject.defineproperty (O,"A", {configurable:true});Throws a TypeErrorObject.defineproperty (O,"A", {enumerable:true});Throws a TypeError (set was undefined previously)Object.defineproperty (O, "a", {set: function () {}}); //throws a TypeError (even though the new get does exactly the same thing) object.defineproperty (o, " a ", {get: function () {return 1;}}); //throws a Typeerrorobject.defineproperty (o, 12}); Console.log (O.A); //logs 1delete o.a; //Nothing Happensconsole.log (O.A); //logs 1
If O.A's configurable attribute is already true, no error will be thrown and the property will be deleted at the end.
Add multiple properties and default values
It is important to consider the default attribute values given by the attribute, typically when you assign a value to an object's properties using the dot operator and Object.defineproperty (), the default value for the property in the data descriptor is different, as shown in the following example.
var o = {};o.a = 1; Equivalent to:object.defineproperty (O, "a", {value: 1, writable: true, configurable: true, enumerable: true}); //On the other hand,Object.defineproperty (O, "a", {value: 1}); Equivalent to:object.defineproperty (O, "a", {value: 1, writable: false, Configurable: false, Enumer Able: false});
Setters and Getters
The following example shows how to implement a self-archiving object. When the temperature property is set, the archive array gets a log.
functionArchiver() {var temperature =Nullvar archive = [];Object.defineproperty (This' Temperature ', {get:function () {Console.log ( ' get! '); return temperature;}, set: Functionthis.getarchive = function< Span class= "Hljs-params" > () {return Archive;};} var arc = new archiver (); arc.temperature; //' get! ' Arc.temperature = 11;arc.temperature = 13;arc.getArchive (); Span class= "Hljs-comment" >//[{val:11}, {val:13}] /span>
Example 2
var pattern = {get:function() {Return' I alway return this string,whatever you have assigned '; }, set:function () { this.myname = ' This is my name string ';}}; function testdefinesetandget() { Object.defineproperty (this, ' myproperty ', pattern);} var instance = new Testdefinesetandget (); instance.myproperty = ' Test '; ' I alway return this string,whatever you have assigned ' Console.log (instance.myproperty); //' This is my name string ' Console.log (instance.myname);
A detailed description of the JavaScript Object.defineproperty () method