[ES6] Ruan Yifeng ES6 Learning (6) Proxy

1 Introduction

es6ProxyA new type called Proxy"Agent" has been newly designed in . The original meaning of this word is "proxy ". Interception", the outside world's access to this object must first pass through this layer of interception .

give a simple example

For example, the agent of Maotai liquor, with this agent, we can not get liquor directly from Maotai company, we must go through this agent

How much money the agent says, is how much money, if the agent says no, there is no

ProxyThe proxy is an object. After this object is proxied, we cannot directly access this object, but must access it through a proxy.

For example, if you want to get the value of a certain attribute, if the agent says there is no value, it will not exist, and the agent will return whatever value it wants to return to you.

ProxyThe access proxy is specially set up for the object, whether it is reading or writing, it must go through the proxy, and the proxyreading and writing process of the object can be easily monitored through the proxy.

2. use

How to use Proxythe read and write process of the monitoring object? Define an object, there is an attribute and attribute personin the object , and then create a proxy object through the method , which is the interception set for the object.nameheightnew Proxypersonproxyperson

ProxyThe constructor needs 2 parameters, one is the target object that needs to be proxied, and the other is the processing object of the proxy. In this processing object, the get()access of the object property can be monitored through the method, and set()the process of setting the property of the object can be monitored through the method.

const person={
    
    
    name:'zzz',
    height:185
}
const proxy=new Proxy(person,{
    
    
    get(){
    
    //监视对象属性的访问

    },
    set(){
    
    //监视对象设置属性的过程

    }
})

3. Proxy instance method

1. get() method

getThe method is used to intercept the read operation of a property, and can accept three parameters, in order ofThe target object, attribute name and proxyinstance itself (the object that the operation behavior is aimed at), the last parameter is optional

const proxy=new Proxy(person,{
    
    
    get(target,propKey){
    
    // 目标对象  访问的属性名
        console.log(target,propKey); // {  } , name
    },
    set(){
    
    

    }
})
console.log(proxy.name); // zzz

// 第二个例子
var person = {
    
    
  name: "张三"
};

var proxy = new Proxy(person, {
    
    
  get: function(target, propKey) {
    
    
    if (propKey in target) {
    
    
      return target[propKey];
    } else {
    
    
      throw new ReferenceError("Prop name \"" + propKey + "\" does not exist.");
    }
  }
});

proxy.name // "张三"
proxy.age // 抛出一个错误

insert image description here
get()The normal logic of the method should be to judge whether there is an accessed attribute name in the proxy target object, return the corresponding value if it exists, or return undefineda default value if it does not exist

get(target,propKey){
    
    
    return propKey in target? target[propKey]:'default'
},

//分别打印存在的属性和不存在的属性
console.log(proxy.name); //zzz
console.log(proxy.age); //default

2. set() method

set()The method is used to intercept the assignment operation of a property, and can accept four parameters, in order ofTarget object, attribute name, attribute value and Proxy instance itself, where the last parameter is optional

set(target,propKey,value){
    
    
    console.log(target,propKey,value);
}

proxy.sex='男'

The console will print out the written properties and property values
insert image description here

set()The normal logic of the method should be to set the specified attribute for the proxy target, and do some data verification before setting it. For example, if the attribute name is height, then it is necessary to judge whether it is a number, or throw an error

set(target,propKey,value){
    
    
    if(propKey=== 'height'){
    
     //判断属性名是否为height
        if(!Number.isInteger(value)){
    
    //判断是否为整数
            throw new TypeError(`${
      
      value} is not an int`)
        }
    }
    target[propKey]=value
}

setThe fourth parameter of the method receiverrefers to the object where the original operation behavior is located, usually proxythe instance itself

const handler = {
    
    
	set: function(obj, prop, value, receiver) {
    
    
		obj[prop] = receiver;
		return true;
	}
}
const proxy = new Proxy({
    
    }, handler);
proxy.foo = 'bar';
proxy.foo === proxy;

3. apply() method

applyMethod intercept function call, calland applyoperation

Accepts three parameters, which are == target object, target object's context object ( this), and target object's parameter array.

var handler = {
    
    
	apply(target, ctx, args){
    
    
		return Reflect.apply(...arguments);
	}
};

In the following code, the variable pis Proxyan instance of , when it is called as a function ( p()), it will be applyintercepted by the method and return a string.

var target = function(){
    
     return 'I am the target'};
var handler = {
    
    
  apply: function(){
    
    
    return 'i am the proxy';
  }
}
var p = new Proxy(target, handler);
console.log(p());  // "i am the proxy"

4. Why does Proxy exist?

Because before ES6, we used Object.defineProperty()to set the listener to monitor the acquisition and rewriting of object properties. But if there are some other operations in it, we can't monitor it, so in order to solve such a problem, a Proxyproxy is added in ES6. ProxyCan help us monitor operations in objects.

compare the two

Object.defineProperty

let info = {
    
    
  name: 'dmc',
  age: 20
}

Object.defineProperty(info, 'name', {
    
    
  get() {
    
    
    console.log('get--获取info的name值')
    return 'dl'
  },
  set() {
    
    
    console.log('set--设置info的name值')
  }
})

console.log(info.name) // get--获取info的name值   dl
info.name = 'dmc'  // set--设置info的name值

Proxy

let info = {
    
    
  name: 'dmc',
  age: 20
}

let infoProxy = new Proxy(info, {
    
    
  get(target, key) {
    
    
    console.log('获取对象属性')
    return target[key]
  },
  set(target, key, newValue) {
    
    
    console.log('设置对象属性')
    target[key] = newValue
  }
})

Guess you like

Origin blog.csdn.net/Bon_nenul/article/details/128221578