Talking about Object.defineProperty(), a must-read for getting started

Adhering to the vision of the world's most difficult-to-understand technology, we will launch directly

First of all, Object.defineProperty() can be understood as the operation (read/write) of properties in another object through an object proxy

Of course, it can also be an object agent operating on the value of a variable

This sentence may be a mouthful, read it several times, if you really don’t understand it, just look at Example 2

Don't talk nonsense and go directly to the code

Detailed legend

Here is a person proxying the value of number === Of course, it can also be an object proxying the value operation of a variable

The three parameters of Object.defineProperty() are:

person : To add a key to that object

'age' : newly added key name// Note that this is a string

{} : The third parameter is an object, which contains get and set methods

Example 2:

Here is the operation of an object proxy on the properties of another object

Note: At this time, obj2 uses the value of x in obj, but x in boj2 is the newly added key for obj2. Instead of using x in obj directly.

Other configuration items

value: value,

enumerable: true, // enumerable indicates whether it can be enumerated, the added property name cannot be read when traversing, the default value is false

writable: true, //Whether the control attribute can be modified, the default value is false

configurable: true, // Control whether the attribute can be deleted, the default value is false

Note that the above configuration cannot coexist with the get() and set() methods, otherwise the following error will be reported

Uncaught TypeError: Invalid property descriptor. Cannot both specify accessors and a value or writable attribute, #<Object>

at Function.defineProperty (<anonymous>)

Guess you like

Origin blog.csdn.net/guojixin12/article/details/129131161