Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Proxy and Relection enable JavaScript as a language to support Meta programming, allowing programs to implement programs. Vue3 has also moved from getters and setters to proxies and relections for responsive data implementation, so it’s worth taking a good look at this section and taking some time to tidy it up in order to help you understand the new features of JavaScript.

For most operations on objects, there is a so-called “inner method” in the JavaScript specification that describes how it works at the lowest level. For example, [[Get]] reads the inner method of an attribute, and [[Set]] writes the inner method of an attribute. These methods are only used in the specification, so we can’t call their names directly.

let proxy = new Proxy(target, handler)
Copy the code
Internal methods Interceptor method Triggering scenarios
[[Get]] get Reads the properties
[[Set]] set Write attributes
[[HasProperty]] has inoperation

Implement the default value by setting the interceptor to the GET method

The most common interceptors are those set for read/write properties. To intercept reads, the handler should have a GET (Target, property, receiver) method.

The interceptor is triggered when a property is read with the following arguments.

let target = {};
let proxy = new Proxy(target, {}); / / air handler

proxy.test = 5; // writing to proxy (1)
alert(target.test); / / 5,

alert(proxy.test); / / 5,

for(let key in proxy) alert(key); 
Copy the code
  • Target – is the target object passed to the New Proxy as the first argument
  • Property – The name of the property
  • Receiver – If the target property is a getter, the receiver parameter specifies the object on which the function is called, i.ethisObject to which. This is usually the Proxy object itself (which can be an object that inherits from the Proxy). We will ignore this parameter for the moment and explain it in more detail later.

Set the default value returned by GET

Normally when trying to get an item from an array that does not exist, such as if the index is out of bounds, we get undefined results by default, but we’ll wrap an ordinary array in a proxy that can catch reads and return 0 if there is no such property.

let numbers = [0.1.2];

numbers = new Proxy(numbers, {
  get(target, prop) {
    if (prop in target) {
      return target[prop];
    } else {
      return 0; // default value}}}); alert( numbers[1]);/ / 1
alert( numbers[123]);/ / 0
Copy the code

I’ll bring you more examples later, and I hope you can support me.