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

  • JavaScriptIn theProxyWhat is? What can you do?
  • Vue3.0Why to start withProxyInstead ofObject.defineProperty

ProxyWhat 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:targetThat’s who you want to represent; whilehandlerIs a function object that defines all the functions you want to replacetargetThe operation objects managed by the agent include:
    • *handler.has(target, prop): inOperator 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.getPrototypeOfMethod
    • handler.setPrototypeOf(): Object.setPrototypeOfMethod
    • handler.isExtensible(): Object.isExtensibleMethod
    • handler.preventExtensions(): Object.preventExtensionsMethod
    • handler.getOwnPropertyDescriptor(): Object.getOwnPropertyDescriptorMethod
    • handler.defineProperty(): Object.definePropertyMethod
    • handler.deleteProperty(): deleteOperator
    • handler.ownKeys(): Object.getOwnPropertyNamesMethods andObject.getOwnPropertySymbolsMethod
    • handler.construct()A catcher for the: new operator
  • Pay attention to: If an attributeconfigurable || Do not write, the property cannot be proxiedProxyAn error will be reported when accessing this property.
  • * Traps are all that will be covered in this article

ProxyWhat 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 directlyundefined
  • You can also usehasTrap 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:ProxyTo be effective, agents must be targetedProxyInstead 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
  • useProxyWrapping allows the constructor to make direct function calls as well

Five: Deep value judgment (see the code)

  • Several issues that need to be addressed

    1. Get data for interception
    2. xxx.xxx.xxx...No matterundefinedWhere can’t the error be reported
    3. Proxyget()The parameters passed in must be objects
  • Traditional way of deep value is tedious, using Proxy can simplify unnecessary code

  • But whentarget[prop]undefinedThe time,Proxy get()The input of theta becomes thetaundefined, butProxyThe first entry must be an object
  • I need obj to be zeroundefinedIn order to be able to deep value, so use an empty function to set interception, usingapplyTrap processing

  • Our ideal would be if the property is zeroundefinedIt 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 zeroundefinedI also need to use itProxyFor 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 hereget(undefined).xxxIs the correct value, because to get the value you must execute to get it
  • So you just have to do all theundefinedProperties accessed later default toundefinedThat’s why we need an agentundefinedAfter the return object
  • Also to solve the problem of infinite loop execution when first detectedundefinedStop 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:ProxyIn 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.definePropertyBy setting for the propertygetter/setterIt 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 itVue.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 topush/pop/shift/unshift/splice/sort/reverseThese 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

  • ProxyPerformance thanPromiseworse
  • ProxyAs 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.0Dropped support for IE in theVue 3.0Will 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 supportProxyAll interception methodsPolyfillPlan, there is onegoogleWrite theproxy-polyfillOnly supportget/set/apply/constructFour intercept

Say a lot about decorators

  • Implemented in ES7DecoratorWhich corresponds to the decorator pattern in the design pattern.
  • If it’s easy to distinguishProxyDecoratorCan be summarized as:ProxyThe core role of the agent is to control the external access to the internal agent,DecoratorThe 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