The Proxy intercepts operations such as reading and function invocation of the target object, and then processes the operations. It does not operate directly on objects, but rather acts like a proxy mode, operating through objects’ proxy objects, and as it does so, additional operations can be added as needed. There are mainly the following situations:

  1. Get object properties
  2. Sets the object property value
  3. Traverse object
  4. Checks whether the object has a corresponding attribute
  5. Deleting object Properties
  6. Function calls, call and apply
  7. The new command

Basic usage

let obj = {name:'dylan'}
let myproxy = new Proxy(obj,{}) 
// Two arguments, the first is the target to be proppated, such as obj object, and the second is an object containing the interception operation to be carried out. If empty, no interception operation will be carried out
Copy the code

get(target, prop)

Interception is performed when the object property is acquired. Add get method to the second parameter object of proxy for interception (the following method is also used). Parameter target represents the object of proxy, parameter prop represents the name of the property passed (parameter name can be customized).

let obj = {name : 'dylan'}
obj = new Proxy(obj,{ get(target,prop){
    console.log(target,prop)   // Here we can write some code before the object is fetched
    return target[prop]        // The value of return is the value of the object property}}) example: ExecuteconsoleWhen.log(obj.name), the object name property is obtained and the proxy get function is executed// Proxy array example
 let arr = [5.6.7]
 arr = new Proxy(arr,{
      get(target,prop){
        console.log(target,prop)
        return prop in target ? target[prop] : 'err'}})console.log(arr[2])
Copy the code

set(target, props, val)

Intercepts when an object property value is set. Target represents the object of the agent, props represents the property name, and val represents the value to be set. Set needs to return a Boolean value.

let obj = {name : 'Dylan'}
obj = new Proxy(obj, {
  set(target, props,val){
    console.log(target,props,val) // Target is the object obj,props is the 'name' property passed in, val is 'newName'
    target[props] = val  // If this is set to target[props] = 'HHH' then it will be set to HHH
    return true
  }
})
obj.name = 'newName'  // Set the object property value
console.log(obj.name)  / / print 'newName'
Copy the code

has(target, prop)

Interception to determine whether an object has a property. Target and prop represent the object of the proxy and the name of the property passed, respectively. You need to return a Boolean value.

let range = {
  start:1.end:5
}
range = new Proxy(range,{
  has(target,prop){
   return prop >=target.start && prop <= target.end
  }
})
console.log(0 in range)  // 0 is not between 1 and 5, return false
Copy the code

ownKeys(target)

Interception when an object is traversed. Target represents the proxy object and returns an array. When we use the Object. GetOwnPropertyNames (), Object, getOwnPropertySymbol (), Object. Keys (), for… In each of these methods triggers the ownKeys method as it traverses.

Let's say we don't want a property of an object to be traversedlet userinfo = {
    name: 'dylan'._password: '123'   // We don't want the password that starts with an underscore to be traversed
 }
userinfo = new Proxy(userinfo,{
   ownKeys(target){
     return Object.keys(target).filter(key= >! key.startWith('_')) // Filter attributes beginning with an underscore}})console.log(Object.keys(userinfo)) // print only ['name']
Copy the code

deleteProperty(target, prop)

Interception when an object property is deleted. Receives two parameters, target and prop, respectively, referring to the object of the proxy and the property to be removed. Returns a Boolean value.

Let's say we don't want the underlined attributes of the object to be deletedlet obj = {
    name : 'dylan'._password: '123'
}
obj = new Proxy(obj,{
    deleteProperty(target,prop){
      if(prop.startWith('_')) {throw new Error('Undeletable')}else{
        delete target[prop]
        return true}}})try{
  delete obj._password
 }catch(e){ console.log(e.message) }   // Delete failed, will print 'cannot delete'



Copy the code

apply(target, ctx, args)

Used to intercept function calls, call, and reply operations. Target represents the target object, CTX represents the context of the target object, and args represents the array of parameters of the target object.

function sub(a, b){
    return a - b;
}
sub = new Proxy(sub,{
  apply(target,ctx,args){
   console.log('apply')
   returntarget(... args)*2;   // Multiply the result of the function by 2}})console.log(sub(5.2))  / / print 6
Copy the code

construct(target, args)

Used to intercept the new command. The return value must be an object.

class Exam { 
  constructor (name) {  
      this.name = name 
  }
}
let ExamProxy = new Proxy(Exam, {
  construct(target, args, newTarget) {
  console.log('construct')
  return newtarget(... args) }})console.log(new ExamProxy('dylan'))
Copy the code

Comprehensive example

let obj = {
   name:'dylan'.age:18._secret:'123'
}
obj = new Proxy(obj, {
   get(target, prop){ return target[prop] },
   set(target, prop, val){ 
        target[prop] = val 
        return true 
       },
   has(target,prop){ return prop in target },
   ownKeys(target){ 
        return Object.keys(target).filter(key= >! key.startWith('_'))})},deleteProperty(target, prop){
        deleteProperty(target,prop){
      if(prop.startWith('_')) {throw new Error('Undeletable')}else{
        delete target[prop]
        return true}}})console.log(obj.name)       / / triggers the get
obj.age = 17                / / triggers the set
console.log('name' in obj)  / / has triggered
for(let key inobj) {... }/ / triggers ownKeys
delete obj.age              / / triggers deleteProperty
Copy the code