introduce
The set method is used to intercept the assignment of an attribute and can accept four parameters.
Target object, attribute name, attribute value and Proxy instance itself, the last parameter is optional

  • demo1 assumes that the Person object has an age attribute, which should be an integer no more than 200. Proxy can be used to ensure that the value of the age meets the requirements.
 {
            let validator = {
            set:function (obj,prop,value){
                if(prop === 'age'){
                    //Judge whether it's an integer or not
                    if(!Number.isInteger(value)){
                        throw new TypeError('the age is not an integer');
                    }
                    if(value>200){
                        throw new RangeError('The age seems invalid');
                    }
                }
                //For age attributes and other attributes that satisfy the conditions, save them directly
                obj[prop] = value;
            }
        };
        let person = new Proxy({},validator);
        person.age = 100;
        console.log(person.age);
        }
  • demo2 sometimes sets internal attributes on objects. The first character of the attribute name starts with an underscore to indicate that these attributes should not be used externally. Combining get and set methods, we can prevent these internal attributes from being read and written externally.
{
    const handler = {
    get (target,key){
        invariant(key,'get');
        return target[key];
    },
    set (target,key,value){
        invariant(key,'set');
        target[key] = value;
        return true;
    }
};

function invariant (key,action) {
    if(key[0] === '_'){
        throw new Error(`Invalid attempt to ${action} private "${key}"property`)
    }
}

const target = {};
const proxy = new Proxy(target,handler);
}
//console.log("proxy._prop",proxy._prop);
//Invalid attempt to get private "_prop" property at invariant
//proxy._prop = "c";
//Invalid attempt to get private "_prop" property at invariant
  • Below demo3 is an example of the fourth parameter of the set method
{
    const handler = {
        set:function(obj,prop,value,receiver) {
            obj[prop] = receiver;
        }
    };
    const proxy = new Proxy({},handler);
    proxy.foo = 'bar';
    console.log(proxy.foo === proxy);//true
}
//In the above code, the fourth parameter receiver of the set method refers to the object in which the original operation is located, usually the proxy instance itself.

  • demo4 See the following example
{
    const handler = {
        set :function (obj,prop,value,receiver) {
            obj[prop] = receiver
        }
    };
    const proxy = new Proxy({},handler);
    const myObj = {};
    Object.setPrototypeOf(myObj,proxy);
    //The Object.setPrototypeOf() method sets the prototype of a specified object (that is, the internal [[Prototype]] attribute) to another object or null.
    myObj.foo = 'bar';
    console.log(myObj.foo === myObj);//true
}
//When setting the value of myObj.foo property in the above code, myObj has no foo property, so the engine will find the foo property on the prototype chain of myObj.
//However, myObj's prototype object proxy is a Proxy instance, and setting its foo attribute triggers the set method. At this time,
//The fourth parameter, receiver, points to myObj, where the original assignment behavior is located.

//Note: If an attribute of the target object itself is not writable and configurable, the set method will not work.
  • demo5
{
    const obj = {};
    Object.defineProperty(obj,'foo',{
        value:'bar',
        writable:false,
    });
    const handler = {
        set :function (obj,prop,value,receiver) {
            obj[prop] = 'baz';
        }
    };
    const proxy = new Proxy(obj,handler);
    proxy.foo = 'baz';
    console.log("proxy.foo",proxy.foo);//proxy.foo bar
}
//In the code above, the obj.foo property is not writable, and the set agent for this property by Proxy will not take effect to control whether the writable property is writable or not.

  • demo6 Notes that in strict mode, if the set agent does not return true, it will report an error.
{
    'use strict';
    const handler ={
        set:function (obj,prop,value,receiver) {
            obj[prop] = value;
            //Whether or not you have the following line, you will make a mistake.
            //return true;

        }
    }
    const proxy = new Proxy({},handler);
    proxy.foo='bar';
    console.log("proxy.foo",proxy.foo=='bar');
}

//Whether there is any renturn on the above example does not seem to matter. This example is taken from the last instance of Ruan Yi Feng ECMAScript6 entry Proxy set method.

The example is from Ruan Yifeng's introduction to es6. If the writing is incomplete, welcome to correct it.