一、Object.defineProperty
Definition: Object.defineProperty()
The method defines a new property directly on an object, or modifies an existing property of an object, and returns this object
Why can it be responsive? via defineProperty
two properties, get
andset
- get
The property's getter function, which is called when the property is accessed. No parameters are passed in during execution, but the this object will be passed in (due to the inheritance relationship, this here is not necessarily the object defining the property). The return value of this function will be used as the value of the property
- set
The setter function of the property, when the property value is modified, this function will be called. This method accepts a parameter (that is, the new value to be assigned), which will be passed in the this object at the time of assignment. The default is undefined
define a reactive functiondefineReactive:
Call defineReactive
, trigger method when data changes update
, realize data responsive
When there are multiple objects key
, traversal is required
If there are nested objects, you also need to defineReactive
recurse in
When key
assigning an object, you also need to set
recurse in the attribute
The above example can realize the basic response to an object, but there are still many problems
Now delete and add attributes to an object, which cannot be hijacked
When we listen to an array, it doesn't work so well
It can be seen that the data api
cannot be hijacked, so that the data responsiveness cannot be realized.
So in Vue2
, add set
, delete
API, and api
rewrite the array method
Another problem is that if there is a deep nested object relationship, it needs to be monitored deeply, which causes a huge performance problem
Two , proxy
Proxy
The monitoring is for an object, then all operations on this object will enter the monitoring operation, which can completely proxy all attributes
The code is shown below:
Define a reactive methodreactive
Test the operation of simple data and find that it can be hijacked and then test the nested object. At this time, it is not so OK
If you want to solve it, you need to get
perform a layer of proxy on top of it
3. Summary
Object.defineProperty
Can only traverse object properties for hijacking
Proxy
Directly hijack the entire object and return a new object, we can only operate the new object to achieve responsive purposes
Proxy
You can directly monitor the changes of the array ( push
, shift
, splice
)
Proxy
There are as many as 13 interception methods, not limited to apply
, ownKeys
, deleteProperty
, has
etc., which are Object.defineProperty
not available
Proxy
Not compatible with IE, nor polyfill
, defineProperty
can support IE9
references
https://developer.mozilla.org/zhCN/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty