Enumeration of methods in Proxy

Handler method triggered
get Read a property
set Write a property
has The in operator
deleteProperty The delete operator
getPrototypeOf Object.getPrototypeOf()
setPrototypeOf Object.setPrototypeOf()
isExtensible Object.isExtensible()
preventExtensions Object.preventExtensions()
getOwnPropertyDescriptor Object.getOwnPropertyDescriptor()
defineProperty Object.defineProperty()
ownKeys Object. GetOwnPropertyNames (), Object. GetOwnPropertySymbols ()
apply Call a function
construct Call a function with new

Application of Proxy method

get()

The GET method listens for a read of a property and can take three parameters: the Proxy target object, the name of the read property, and the Proxy instance itself (strictly speaking, the object against which the action is directed), the last of which is optional.

const person = {
    name: 'Lucky'.age: 20,}const personProxy = new Proxy(person, {
    // Set to receive two parameters: the proxy target object and the read property name
    get(target, property) {
        if (property in target) {
           return target[property]
        }
        throw new ReferenceError(`Property '${property}' does not exist.`); }})console.log(personProxy.name); // Lucky
console.log(personProxy.add); // Error Property 'add' does not exist.
Copy the code

The above code sets up in GET to throw an error if it reads properties of the target object that do not exist. Normally, reading non-existent properties of an object returns undefined.

set()

The set method is used to listen to the assignment operation of an attribute. It can accept four parameters: the Proxy target object, the name of the attribute set, the value of the attribute set, and the Proxy instance itself. The last parameter is optional.

const person = {
    name: 'Lucky'.age: 20,}const personProxy = new Proxy(person, {
    // Three parameters: the proxy target object, the name of the property to be written, and the value of the property
    set(target, property, value) {
        if (property === 'age') {
            if (!Number.isInteger(value)) {
                throw new TypeError(` '${value}' is not a int`)
            }
        }
        target[property] = value
    },
})

personProxy.age = 123
personProxy.age = 'woshiLucky' // error 'woshiLucky' is not an int
Copy the code

The above code detects that the age field must be numeric when changing the value of an object attribute, and raises an error if the value is not numeric.

has()

The HAS method is used to listen for HasProperty operations that take effect if an object has a property. A typical operation is the IN operator. The HAS method can take two parameters, the proxy target object and the name of the property to be queried.

const person = {
    name: 'Lucky'.age: 20,}const personProxy = new Proxy(person, {
    // Two parameters: the proxy target object and the name of the property to determine whether it exists
    has(target, property) {
        // return the result inversely
        return! (propertyin target)
    },
})

console.log('age' in personProxy); // false
console.log('add' in personProxy); // true
Copy the code

The above code detects the use of the IN operator and reverses the result so that the properties contained in the object return false.

deleteProperty()

The deleteProperty method listens for the DELETE operator. If the method throws an error or returns false, the current property cannot be deleted by the delete command.

const person = {
    name: 'Lucky'.age: 20,}const personProxy = new Proxy(person, {
    // Two parameters: the proxy target object and the attribute name
    deleteProperty (target, property) {
        // No processing is done when the attribute is ageproperty ! = ='age' && deletetarget[property]; }})delete personProxy.age
delete personProxy.name
console.log(person);
Copy the code

The above code listens for the DELETE operator and does not delete the age field.

getPropertyOf()

The getPropertyOf method is primarily used to listen for object prototypes. Listen for the Object.getProtoTypeof () method. Receives a parameter, proxy target object.

const person = {
    name: 'Lucky'.age: 20,}const person1 = {}

const personProxy = new Proxy(person, {
    // Parameter: the current target object
    getPrototypeOf(target) {
        returnperson1; }})console.log(Object.getPrototypeOf(personProxy) === person); // false
Copy the code

The object of the proxy in the above code is Person, and the object of Person1 is returned when listening for the getPrototypeOf method, so personProxy is not equal to Person

setPrototypeOf()

The setPrototypeOf method is mainly used to listen for setting the Object prototype object.setPrototypeof () method. Receives two parameters: the object to which the stereotype needs to be changed and the object to which the stereotype is provided.

const person = {
    name: 'Lucky'.age: 20,}const person1 = {}

const personProxy = new Proxy(person, {
    // Two parameters: the proxy target object and the attribute name
    setPrototypeOf(target, proto) {
        console.log(target, proto, target === proto);
        if(target ! == proto) {return true
        }
        throw Error('The target object is the same as the current object.')}})Object.setPrototypeOf(personProxy, person1)
Object.setPrototypeOf(personProxy, person) // The target object is The same...
Copy the code

The code above redefines the error message for the prototype chain loop.

isExtensible()

The isExtensible() method is mainly used to listen to determine whether an Object isExtensible(whether new properties can be added to it). The object.isextensible () method returns a Boolean value.

const person = {
    name: 'Lucky'.age: 20,}const personProxy = new Proxy(person, {
    // Parameter: the current target object
    isExtensible(target) {
        console.log('isIn');
        return true; }})Object.isExtensible(personProxy)
// isIn
// true
Copy the code

Print ‘isIn’ with isExtensible

preventExtensions()

The preventExtensions method is mainly used to listen for objects that should be made unextensible, that is, Object. PreventExtensions () should never add new properties. It must return a Boolean or it will be automatically converted to a Boolean. The limit to this method is that proxy.preventExtensions can only return true if the target Object is not extensible (Object. IsExtensible (proxy) is false), otherwise an error will be reported

const person = {
    name: 'Lucky'.age: 20,}const personProxy = new Proxy(person, {
    // Parameter: the current target object
    preventExtensions(target) {
        console.log('isIn');
        Object.preventExtensions(target);
        return true; }})Object.preventExtensions(personProxy)
Copy the code

getOwnPropertyDescriptor()

GetOwnPropertyDescriptor method is mainly used to monitor Object. GetOwnPropertyDescriptor () Object. GetOwnPropertyDescriptor () method returns the specified Object on a has its own corresponding attribute descriptor. (Own properties are those that are directly assigned to the object and do not need to be looked up on the stereotype chain.)

const person = {
    name: 'Lucky'.age: 20,}const personProxy = new Proxy(person, {
    // Two parameters: the proxy target object and the attribute name
    getOwnPropertyDescriptor(target, property) {
        if (property === 'name') return
        return Object.getOwnPropertyDescriptor(target, property); }})console.log(Object.getOwnPropertyDescriptor(personProxy, 'age')); 
// { value: 20, writable: true, enumerable: true, configurable: true }
console.log(Object.getOwnPropertyDescriptor(personProxy, 'name'));
//undefined
Copy the code

The above code is handled when name is obtained, returning undefined

defineProperty()

The defineProperty method is mainly used to listen for the Object.defineProperty() method. The object.defineProperty () method directly defines a new property on an Object, or modifies an existing property of an Object, and returns the Object

const person = {
    name: 'Lucky'.age: 20,}const personProxy = new Proxy(person, {
    // Two parameters: the proxy target Object, the property name, and the property descriptor to define or modify.
    defineProperty(target, property, valueObj) {
        target[property] = valueObj.value;
        return true
    },
})
personProxy.gender = 'female';
console.log(personProxy); // { name: 'Lucky', age: 20, gender: 'female' }
Copy the code

ownKeys()

The ownKeys method is used to listen for the reading of the object’s own properties

  • Object.getOwnPropertyNames()
  • Object.getOwnPropertySymbols()
  • Object.keys()
  • for… In circulation
const person = {
    name: 'Lucky'.age: 20,}const personProxy = new Proxy(person, {
    // Parameter: proxy target object
    ownKeys(target) {
        return Object.keys(target)
    },
})

console.log(Object.keys(personProxy));
Copy the code

apply()

The apply method is primarily used to listen for function calls to call and apply operations. The Apply method takes three parameters: the target object, the target object’s context object (this), and the target object’s parameter array.

const target = () = > 'Target';
const targetProxy = new Proxy(target, {
    // Three parameters: the target object, the context object of the target object (this), and the target object's parameters array
    apply (target, ctx, args) {
        return 'apply'}})console.log(targetProxy()); // apply
Copy the code

construct()

The construct method is mainly used to listen for the new command. The construct method can take three arguments. The target object, the constructor’s argument object, and the constructor that the new command uses when creating the instance object.

class TargetObj {
    construct() {
        this.a = 'new'}}const targetProxy = new Proxy(TargetObj, {
    // Three parameters: the target object, the context object of the target object (this), and the target object's parameters array
    construct (targets, args) {
        console.log(targets, args);
        return args
    }
})

console.log(new targetProxy(1.2.3)); / / [1, 2, 3]
Copy the code