Relect of vue3 source code analysis


![Insert picture description here](https://img-blog.csdnimg.cn/20210207200123723.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0LQND=FFXblQnLmNz803
First look at the source code part of vue 3.x: this createGetter actually encapsulates the content of get in the proxy. Simply put, when we read the object properties, we will return the object properties through proxy's get, and at this time collect dependencies through the track() method, we know that triggering the proxy's get properties, we need to return the properties of the object, why is it used here? The Reflect method does not need to return target[key] to return the object properties.
First look at the following code:

 let obj={
    
    
           a:1,
           get b(){
    
    
               return this.a
           }
        }
        let proxyObj=new Proxy(obj,{
    
    
            get(target,key,receiver){
    
    
                return target[key]
            }
        })
        let childObj=Object.create(proxyObj)
        childObj.a=2
        console.log(childObj.b)//1

We hope that when the a property of the childObj object is changed, the b property of the childObj object can also be changed to follow the a change. But the result is not up to expectations, we assigned a value of 2, and the resulting output b is 1. Because childObj has no b attribute, we did not implement it, and childObj’s __proto__ points to proxyObj, so when we print out childObj’s b attribute, we trigger proxyObj’s get method to get the value of b attribute, and the get method gets The getter in obj, the value of this in the getter in obj points to obj instead of the current childObj. Below use Reflect to get the attributes,

 let obj={
    
    
           a:1,
           get b(){
    
    
               return this.a
           }
        }
        let proxyObj=new Proxy(obj,{
    
    
            get(target,key,receiver){
    
    
                return Reflect.get(target,key,receiver)
            }
        })
        let childObj=Object.create(proxyObj)
        childObj.a=2
        console.log(childObj.b)//2

As a result, childObj.b is 2. When we print out childObj.b, we still get b from the prototype chain, and go through the proxy proxy. Because we now use Reflect.get() to get the properties, getter and receiver are specified in the target object. It is the this value when the getter is called. Now the getter is called by childObj and this points to childObj, so the output is 2.

Guess you like

Origin blog.csdn.net/weixin_44494811/article/details/113745942