Ask a good

Hello, I’m Dreyven. It’s nice to meet you again.

When complaining about why the holiday is so short on the sixth day, it has come to the seventh day.

I wish you all a happy seventh day and a happy start!!

Advertising time:

  • Follow me at github: github.com/dravenww
  • Welcome to Star my Blob: blog address

The text begins here.

Vue2 proxy implementation

As we all know, the way to implement proxies in Vue2 is through data hijacking, using Object.defineProperty; A simple example is as follows:

var obj = {}; var initValue = 20; Object.defineProperty(obj, "age", { get: function () { console.log('get') return initValue; }, set: function (value) { console.log('set') initValue = value; }}); console.log(obj.age); obj.age = 22; console.log(obj.age);Copy the code

In the code above, the console would print:

Data hijacking in Vue2 is implemented in this way, where get collects dependencies (Depend) and set triggers dependencies (notify). Vue-definereactive source code direct

Vue2 rewraps array methods, including push, POP, Shift, unshift, splice, sort, reverse. Vue2 rewraps array methods, including push, POP, Shift, unshift, splice, sort, reverse. Vue array rewraps source code directly

About how to achieve observe in Vue2, I don’t want to explain too much here. Please read the article Vue2 source code interpretation – observe

The Vue2 proxy is faulty

In Vue2, even with array reencapsulation, there are problems as follows:

Var list = [' Tom ', 'jack', 'draven', 'ifil'] var list = [' Tom ', 'jack', 'draven'] List [2] = 'luckyDraven'; // List [2] = 'luckyDraven';Copy the code

Vue2 provides a Vue.$set method to compensate for the array modification, but it also adds extra work for developers. This part is also explained in the official documentation of Vue2. About array

The Proxy Vue3

Vue3 abandons data hijacking and instead uses Proxy+Reflect to implement data Proxy.

What is a Proxy

Proxy objects are used to create a Proxy for an object to intercept and customize basic operations (such as property lookup, assignment, enumeration, function calls, and so on). The Proxy constructor syntax is:

const p = new Proxy(target, handler)
Copy the code
  • Target: The target object (which can be any type of object, including a native array, a function, or even another Proxy) to be wrapped with a Proxy.
  • Handler: An object that typically has functions as attributes that define the behavior of agent P when performing various operations.

The handler can contain the following methods (also called catchers) :

// Object.getProtoTypeof method's catcher. Handler.getprototypeof () // object.setProtoTypeof method's catcher. Handler.setprototypeof () // Object.isextensible. Handler.isextensible () // Object.preventExtensions method catcher. Handler. PreventExtensions () / / Object. GetOwnPropertyDescriptor trap method. Handler. GetOwnPropertyDescriptor () / / Object. DefineProperty trap method. Handler.defineproperty () // The catcher for the in operator. Handler.has () // The catcher for the property read operation. Handler.get () // The catcher for the property setting operation. Handler.set () // the trap for the delete operator. Handler. DeleteProperty () / / Object. GetOwnPropertyNames method and Object. The capture of getOwnPropertySymbols method. Handler.ownkeys () // The catcher for the function call operation. Handler.apply () // the catcher for the new operator. handler.construct()Copy the code

Here’s an official example:

const handler = { get: function(obj, prop) { return prop in obj ? obj[prop] : 37; }}; const p = new Proxy({}, handler); p.a = 1; p.b = undefined; console.log(p.a, p.b); // 1, undefined console.log('c' in p, p.c); // false, 37Copy the code

In the simple example above, the default return value is 37 when no attribute name exists in the object. The code above shows how to use the GET Handler. For detailed description, go to Proxy on the official website

What is a Reflect

Reflect is a built-in object that provides methods to intercept JavaScript operations. These methods are the same as the proxy Handlers method. Reflect is not a function object, so it is not constructible.

Unlike most global objects, Reflect is not a constructor, so it cannot be called with the new operator or as a function. All attributes and methods of Reflect are static (just like Math objects).

The Reflect object provides the following static methods, which have the same name as Proxy Handler Methods.

Grammar:

// Call a function and pass in an array as an argument. // Similar to function.prototype.apply (). Reflect.apply(target, thisArgument, argumentsList) // Apply new to the constructor, equivalent to executing new target(... The args). Reflect.construct(target, argumentsList[, newTarget]) // similar to Object.defineProperty(). DefineProperty (target, propertyKey, Attributes) returns true reflect.defineProperty (target, propertyKey, Attributes) // as the function's delete operator, equivalent to delete target[name]. Reflect.deleteproperty (target, propertyKey) // Gets the value of a property on the object, similar to target[name]. Reflect. Get (target, propertyKey receiver], [) / / similar to the Object. The getOwnPropertyDescriptor (). // If this property exists in the object, It returns the corresponding property descriptors, otherwise it returns undefined. Reflect the getOwnPropertyDescriptor (target, propertyKey) / / similar to the Object. The getPrototypeOf (). Reflect.getprototypeof (target) // Determines whether an object has an attribute, which is exactly the same as the in operator. Reflect.has(target, PropertyKey) // Similar to Object.isextensible ().reflect.isextensible (target) // Returns an array containing all its own properties (excluding inherited properties). // (similar to Object.keys() but not enumerable).reflect.ownkeys (target) // Similar to Object.preventExtensions(). Return a Boolean. Reflect. PreventExtensions (target) / / the value assigned to the attribute of the function. Returns a Boolean, true if the update succeeded. Reflect.set(target, propertyKey, value[, receiver]) // The function that sets the object prototype. Returns a Boolean, true if the update succeeded. Reflect.setPrototypeOf(target, prototype)Copy the code

Here’s an example:

  • Checks whether an object has a specific property

    const duck = {
      name: 'Maurice',
      color: 'white',
      greeting: function() {
        console.log(`Quaaaack! My name is ${this.name}`);
      }
    }
    
    Reflect.has(duck, 'color');
    // true
    Reflect.has(duck, 'haircut');
    // false
    Copy the code
  • To assign a value to an object, get all properties of the object

    const duck = {
      name: 'Maurice',
      color: 'white',
      greeting: function() {
        console.log(`Quaaaack! My name is ${this.name}`);
      }
    }
    Reflect.set(duck, 'eyes', 'black'); // returns "true" if successful
    
    console.log(Reflect.ownKeys(duck)); // ["name", "color", "greeting", "eyes"]
    Copy the code

implementation

Reading this, you should see a one-to-one correspondence between the Handler section of Proxy and the static methods supported in Reflect.

Vue3 realizes data Proxy completely through Proxy and Reflect. The source code analysis section can be found in this article Vue3 source code interpretation -createReactiveObject.

Vue3 uses different apis to invoke different handlers to implement data proxies. Post a picture of the source code interpretation:

Vue2 and Vue3 proxies are compared

  • Through the Vue2Object.definePropertyArray listening is not supported, only object listening is supported;
  • Take a look at Vue3 using Proxy+Reflect
    var list = ["tom", "jack"]; var proxy = new Proxy(list, { set: function (target, key, value) { Reflect.set(target, key, value); }}); proxy.length = 3; console.log(list); // ["tom", "jack", undefined] proxy[2] = "draven"; console.log(list); // ["tom", "jack", "draven"]Copy the code

As you can see, Proxy+Reflect solves Vue2’s problem of length and direct assignment not listening.

the last

Of course, the advantages of Proxy are not only the above part of the array, but also some other advantages, you can go to the official website for in-depth reading.

Everyone likes something new, but what matters is not the result, but the process of exploration

Thanks for reading and good luck

If you like it, give it a thumbs up and leave