当前位置:网站首页>Proxy reflect usage details

Proxy reflect usage details

2022-06-27 06:02:00 Supreme and peerless

If you just want to be an ordinary Developer , The understanding of these two can be less thorough , But you want to be a framework or component developer , We need to have a deep understanding of it .

1. Listen to the operation of the object

Now there is a need : There is an object , We want to listen to the process of setting or obtaining properties in this object .

We can go through Object.defineProperty Store attribute descriptors to listen for attribute operations . actually vue2 The principle of the response formula is similar to this .

const obj1 = {
        name: "name",
        age: "age"
      }

      Object.keys(obj1).forEach(key => {
        let value = obj1[key]
        Object.defineProperty(obj, key, {
          set: function(newValue) {
            console.log(` Monitor to give ${key} Set the value `);
            value = newValue
          },
          get: function(){
            console.log(` Listen to get ${key} value `);
            return value
          }
        })
      })

The disadvantages of doing so :

  • First Object.defineProperty It is not designed to listen to all the attributes in an object , When we define certain attributes , The original intention is to define common attributes , But later we forced it into a data attribute descriptor .
  • secondly , If we want to listen for richer operations , Compare new attributes 、 Delete attribute , that Object.defineProperty There's nothing we can do .

therefore ES6 There's a new Proxy class .

2.Proxy Basic use of

Proxy Class is used to help us create a proxy .

  • If we want to monitor One Object related operations , We can First create a proxy object (Proxy object );
  • Then all operations on the object , Are done through proxy objects , The proxy object can listen to what we want to do with the original object .

First of all, we need new One Proxy object , And passed in The object to listen to and a processing object , This processing object can be called handler.

const proxy = new Proxy (target, handler) // grammar

Our subsequent operations are Yes Proxy The operation of , Instead of the original object , Because we need to handler Listen inside .

const obj = {
name: "zzz",
age: "18"
}

const proxy = new Proxy(obj, {})

3.Proxy Of set and get Catcher

If we want to listen for some specific operations , You can go to handler Add Corresponding Catcher (Trap)

set and get They correspond to function types ;

set The function has four arguments :

  • target: Target audience ( Listening objects );
  • property: Properties to be set key;
  • value: New attribute value ;
  • receiver: Called proxy object ;

get The function has three arguments :

  • target: Target audience ( Listening objects );
  • property: The acquired property key;
  • receiver: Called proxy object ;
const obj1 = {
        name: "name",
        age: "age"
      }

      const proxy = new Proxy(obj1, {
        has: function(target, key) {
          console.log("has Catcher ", key)
          return key in target
        },
        set: function(target, key, value) {
          console.log("set Catcher ", key)
          target[key] = value
        },
        get: function(target, key) {
          console.log("get Catcher ", key)
          return  target[key]
        },
        deleteProperty: function(target, key) {
          console.log("delete Catcher ")
          delete target[key]
        }
      })
      proxy.name = "sss"

You want to modify the object later , By manipulating the proxy Object can be implemented , And it can realize listening to objects .

4.Proxy All of the catchers

handler.getPrototypeOf()
  • Object.getPrototypeOf Method's catcher .
handler.setPrototypeOf()
  • Object.setPrototypeOf Method's catcher .
handler.isExtensible()
  • Object.isExtensible Method's catcher ( Judge whether the attribute can be added ).
handler.preventExtensions()
  • Object.preventExtensions Method's catcher .
handler.getOwnPropertyDescriptor()
  • Object.getOwnPropertyDescriptor Method's catcher .
handler.defineProperty()
  • Object.defineProperty Method's catcher .
handler.ownKeys()
  • Object.getOwnPropertyNames Methods and Object.getOwnPropertySymbols Method's catcher .
handler.has()
  • in The catcher of the operator .
handler.get()
  • Property read operation catcher .
handler.set()
  • Property sets the catcher for the operation .
handler.deleteProperty()
  • delete The catcher of the operator .
handler.apply()
  • Function call operation catcher .
handler.construct()
  • new The catcher of the operator .

5.Proxy Of construct and apply

There's more in the catcher construct and apply, They are applied to function objects

6.Reflect The function and use of

Reflect yes ES6 New one API, It's a object , It literally means reflection .

It mainly provides a lot of operation Javascript Object method , It's kind of like Object Methods of manipulating objects in ;

  • such as Reflect.getPrototypeOf(target) Be similar to Object.getPrototypeOf();
  • such as Reflect.defineProperty(target, propertyKey, attributes) Be similar to Object.defineProperty();

If we had Object You can do these operations , So why do we need Reflect Such new objects ?

  • It's because in the early days ECMA This kind of... Is not considered in the specification Yes Object itself How to design the operation will be more standardized , therefore Will these API Put it in Object above ;
  • however Object As a constructor , These operations actually It doesn't fit on it ;
  • It also includes some Be similar to in、delete The operator , Give Way JS It seems that there will be some strange ;
  • So in ES6 in Added Reflect, Let's focus on Reflect On the object ;
  • In addition, we are using Proxy when , It can be done Do not operate on the original object ;
const obj1 = {
        name: "name",
        age: "age"
      }

      const proxy = new Proxy(obj1, {
        has: function(target, key) {
          console.log("has Catcher ", key)
          return Reflect.has(target, key)
        },
        set: function(target, key, value, receiver) {
          console.log("set Catcher ", key)
          return Reflect.set(target, key, value, receiver)
        },
        get: function(target, key, receiver) {
          console.log("get Catcher ", key)
          return Reflect.get(target, key, receiver)
        },
        deleteProperty: function(target, key) {
          console.log("delete Catcher ")
          return Reflect.deleteProperty(target, key)
        }
      })
We found that in use getter、setter There was a receiver Parameters of , What is its function ?
  If our source object (obj) Yes setter、getter Accessor properties for , Then you can. adopt receiver To change what's inside this;

7.Reflect Common ways to do it

Reflect.getPrototypeOf(target)
Be similar to Object.getPrototypeOf().
Reflect.setPrototypeOf(target, prototype)
Set the object prototype function . Return to one Boolean, If the update is successful , Then return to
true.
Reflect.isExtensible(target)
Be similar to Object.isExtensible()
Reflect.preventExtensions(target)
Be similar to Object.preventExtensions(). Return to one Boolean.
Reflect.getOwnPropertyDescriptor(target, propertyKey)
Be similar to Object.getOwnPropertyDescriptor(). If there is
This attribute , The corresponding property descriptor is returned , Otherwise return to undefined.
Reflect.defineProperty(target, propertyKey, attributes)
and Object.defineProperty() similar . If the setting is successful, it will return to true
Reflect.ownKeys(target)
Return a containing all its own attributes ( Does not contain inherited properties ) Array of .( Be similar to
Object.keys(), But it won't be affected enumerable influence ).
Reflect.has(target, propertyKey)
Determine whether an object has an attribute , and in Operator It has exactly the same function .
Reflect.get(target, propertyKey[, receiver])
Get the value of an attribute on the object , Be similar to target[name].
Reflect.set(target, propertyKey, value[, receiver])
Functions that assign values to properties . Return to one Boolean, If the update is successful , Then return to true.
Reflect.deleteProperty(target, propertyKey)
As a function delete The operator , Equivalent to execution delete target[name].
Reflect.apply(target, thisArgument, argumentsList)
To call a function , At the same time, you can pass in an array as the call parameter . and
Function.prototype.apply() The function is similar to .
Reflect.construct(target, argumentsList[, newTarget])
On the constructor new operation , Equivalent to execution new target(...args).
原网站

版权声明
本文为[Supreme and peerless]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/178/202206270557369297.html