Vue3.0 uses Proxy instead of Object. DefineProperty. This article will teach you how to use Proxy with examples
This article also includes [front-end knowledge points], direct link
Read this article
JavaScript
In theProxy
What is? What can you do?Vue3.0
Why to start withProxy
Instead ofObject.defineProperty
Proxy
What is the
Explanation refer to MDN, direct link
Noun explanation
- Proxy objects are used to define custom behavior for basic operations (such as property lookup, assignment, enumeration, function call, and so on)
- Proxy is used to modify the default behavior of some operations. It can also be understood as setting up a layer of interception before the target object. All external access must pass this layer of interception first, so it provides a mechanism to filter and modify the external access
grammar
const p = new Proxy(target, handler)
target
: The target object to wrap with the Proxy (this can be any type of object, including native arrays, functions, or even another Proxy)handler
: Handling of various operations on the proxy object (in the case of an empty object, it can be basically understood that the first parameter is done onceShallow copy)
- In short:
target
That’s who you want to represent; whilehandler
Is a function object that defines all the functions you want to replacetarget
The operation objects managed by the agent include:- *
handler.has(target, prop)
:in
Operator that intercepts HasProperty operations - *
handler.get(target, prop)
: a catcher for property read operations - *
Handler. Set (target, prop, value)
: a trap for property setting operations - *
handler.apply(target, object, args)
: a trap for function call operations that intercepts function calls, call, and apply operations handler.getPrototypeOf()
:Object.getPrototypeOf
Methodhandler.setPrototypeOf()
:Object.setPrototypeOf
Methodhandler.isExtensible()
:Object.isExtensible
Methodhandler.preventExtensions()
:Object.preventExtensions
Methodhandler.getOwnPropertyDescriptor()
:Object.getOwnPropertyDescriptor
Methodhandler.defineProperty()
:Object.defineProperty
Methodhandler.deleteProperty()
:delete
Operatorhandler.ownKeys()
:Object.getOwnPropertyNames
Methods andObject.getOwnPropertySymbols
Methodhandler.construct()
A catcher for the: new operator
- *
- Pay attention to: If an attribute
configurable
||Do not write
, the property cannot be proxiedProxy
An error will be reported when accessing this property. - * Traps are all that will be covered in this article
Proxy
What can you do?
Proxy mode is usually useful when you want to do the following:
- Intercepts or controls access to an object
- Reduce the complexity of methods/classes by hiding transactions or auxiliary logic
- Prevents operations that rely heavily on resources from being performed without verification/preparation
Real private variables in javascript/interceptor has… in… Action/give a prompt or prevent a specific action
Traditional methods private variables can be obtained and modified
Proxy sets private variables
- For private variables, you can use a proxy to intercept a request for a property and restrict it or return it directly
undefined
- You can also use
has
Trap to mask the existence of this attribute
-
The has method intercepts hasProperty operations, not hasOwnProperty operations, so has… The in method does not determine whether an attribute is self-owned or inherited
-
Note: from the… In, for… Unable to intercept in
-
To prevent others from deleting the property, to let the person who called the method know that the method is deprecated, or to prevent others from modifying the property
- Pay attention toIf:
Proxy
To be effective, agents must be targetedProxy
Instead of the target object
Two: data verification (see the code)
- Proxy is used for simple data verification
- It is too heavy to add the verification logic directly to the agent processing function. We can directly pull out the verification module and only need to deal with the verification logic. The agent layer does not need to be changed in the future
Third, use proxy to access recorded objects
- Measure the usage or performance of methods or interfaces that rely heavily on resources, perform slowly, or are used frequently
- You can record a wide variety of information without modifying the application code or blocking code execution. And you can record the performance of a feature function with only a few modifications to this code
-
The example above is an agent that listens to the execution of a function, which can be extended to a dot function
-
Why does the Proxy trap use get instead of apply? The answer
Four: common function and constructor compatibility
- If the constructor call is called without the new keyword, the Class object throws an exception directly
- use
Proxy
Wrapping allows the constructor to make direct function calls as well
Five: Deep value judgment (see the code)
-
Several issues that need to be addressed
- Get data for interception
xxx.xxx.xxx...
No matterundefined
Where can’t the error be reportedProxy
的get()
The parameters passed in must be objects
-
Traditional way of deep value is tedious, using Proxy can simplify unnecessary code
- But when
target[prop]
是undefined
The time,Proxy get()
The input of theta becomes thetaundefined
, butProxy
The first entry must be an object - I need obj to be zero
undefined
In order to be able to deep value, so use an empty function to set interception, usingapply
Trap processing
- Our ideal would be if the property is zero
undefined
It returnsundefined
, but still support access to lower-level properties instead of throwing an error - If you follow this line of thinking, it’s obvious when the property is zero
undefined
I also need to use itProxy
For special treatment
So we need a get() method with the following properties
getData(undefined)() === undefined; // true
getData(undefined).xxx.yyy.zzz(); // undefined
Copy the code
- There’s nothing to be concerned about here
get(undefined).xxx
Is the correct value, because to get the value you must execute to get it - So you just have to do all the
undefined
Properties accessed later default toundefined
That’s why we need an agentundefined
After the return object - Also to solve the problem of infinite loop execution when first detected
undefined
Stop execution
Six: Log reporting
- Tencent uses Proxy to report logs
Vue 3.0 Proxy & Object.defineProperty
Proxy
- Hijacking: proxy the whole object, only need to do a layer of proxy can listen to the peer structure of all property changes, including new attributes and deleted attributes
- nature:
Proxy
In essence, it is a kind of metaprogramming non-destructive data hijacking, which is based on the original object to carry on the function derivative without affecting the original object, in line with the design concept of loose coupling and high cohesion
Object.defineProperty
- Hijacking: Only the properties of the object can be hijacked, but the object cannot be directly represented
- Process: Dependencies are collected in GET and subscribers are notified of updates when data is set
- Existing problemsAlthough:
Object.defineProperty
By setting for the propertygetter/setter
It can accomplish the response of data, but it is not a perfect solution to achieve the response of data. In some cases, it needs to be patched or hacked, which is also its defects, mainly manifested in the following two aspects:- Object property additions or deletions cannot be detected
- Cannot listen for array changes
Object.defineproperty cannot listen for newly added attributes
- Solution: Provide the method to manually Observe again. If you need to listen, use it
Vue.set()
Resets the response for adding properties
2. Object.defineProperty cannot listen to all the properties of an Object at once, such as the child properties of an Object property
- Solution: Implement subattribute responsiveness through recursive invocation
3. Object. DefineProperty cannot respond to array operation
- Solution: By traversing and overriding the Array prototype method operation method, but also limited to
push/pop/shift/unshift/splice/sort/reverse
These seven methods, other array methods, and the use of arrays are not detected, and you cannot listen for array index changes and length changes
4. Proxy intercepts more. Object. DefineProperty only has GET and set
5. Proxy performance is faulty
Proxy
Performance thanPromise
worseProxy
As a new standard, the JS engine will continue to be optimized in the long runProxy
- Thoughts on ES6 Proxies Performance
- My view on ES6 Proxy performance
6. Poor Proxy compatibility
Vue 3.0
Dropped support for IE in theVue 3.0
Will not be compatible with incompatible browsers, but after viewing the data and source code found that it is not compatible at all)- There is currently no full support
Proxy
All interception methodsPolyfill
Plan, there is onegoogle
Write theproxy-polyfill
Only supportget/set/apply/construct
Four intercept
Say a lot about decorators
- Implemented in ES7
Decorator
Which corresponds to the decorator pattern in the design pattern. - If it’s easy to distinguish
Proxy
和Decorator
Can be summarized as:Proxy
The core role of the agent is to control the external access to the internal agent,Decorator
The central function of the decorator is to enhance the function of the decorator.
Past oliver
Long [word] baidu and good interview after containing the answer | the nuggets technology essay in the future
Read on to make your interviewer fall in love with you
Remember a painful experience
Front-end performance optimization -HTML, CSS, JS parts
Front-end performance optimization – Page loading speed optimization
Front-end performance optimization – Network transport layer optimization