“This is the 10th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

preface

Proxy can be understood as a layer of “interception” before the target object. All external access to the object must pass this layer of interception. Therefore, Proxy provides a mechanism for filtering and rewriting external access. The word Proxy is used to mean that it acts as a Proxy for certain operations.

grammar

var proxy = new Proxy(target, handler);
Copy the code

All uses of Proxy objects are in this form, except for the handler arguments. Among them:

  • new Proxy()Indicates that a Proxy instance is generated
  • The target parameter indicates the target object to intercept
  • The Handler parameter is also an object that is used to customize interception behavior

If the handler does not set up any interceptions, that is equivalent to going straight to the original object.

let target = {};
let handler = {};
let proxy = new Proxy(target,handler);
proxy.name = Programming samadhi; 
console.log(target.name); // 'programming samadhi'
Copy the code

Another trick is to set the Proxy object to the Object. Proxy property and call it on the object:

let proxy = new Proxy({}, {
  get: function(target, property) {
    return 35; }});let obj = Object.create(proxy);
obj.time / / 35
Copy the code

get()

The get() method intercepts a read of a property and takes three arguments, in order:

  • The target object
  • The property name
  • The proxy instance itself (strictly speaking, the object against which the action is directed) is optional.

The get() method is used as an example. Here is another example of intercepting a read:

let  perosn = {
    name:'james'.age:26.profession:'software'
}

var proxy = new Proxy(perosn,{
    get:function(target,property) {
        if (property in target) {
            return target[property];
        } else {
            throw new ReferenceError("propertype\""+property + "\" does no exit"); }}});console.log(proxy.name,proxy.profession); // james software
console.log(proxy.sex); // Uncaught ReferenceError: propertype"sex" does no exit
Copy the code

set()

The set() method intercepts an assignment to an attribute and takes four arguments, in order:

  • The target object
  • The property name
  • Attribute values
  • Proxy Instance itself, optional.

Given that the Person object has an age attribute, which should be an integer not greater than 200, you can use Proxy to ensure that the value of the age attribute meets the requirements.

let perosn = {
    name:'james'.age:26.profession:'software'
}

let proxy = new Proxy(perosn,{
    get:function(target,property) {
        if (property in target) {
            return target[property];
        } else {
            throw new ReferenceError("propertype\""+property + "\" does no exit"); }},set:function(target,key,value) {
        if(key === 'age') {
            if(value>80) {
                throw ReferenceError("invail");
            } else {
                returntarget[key] = value; }}else {
            returntarget[key]; }}}); proxy.age =60;
console.log(proxy.name,proxy.profession,proxy.age); // james software 60

proxy.age = 99; // Uncaught ReferenceError: invail
Copy the code

apply()

The apply() method intercepts:

  • Function call
  • The call operation
  • The apply operation

The apply() method takes three arguments, which are:

  • The target object
  • Context object of the target object (this)
  • An array of parameters for the target object.
let twice = {
    apply(target, ctx, agrs) {
        return Reflect.apply(... arguments) *2; }};function sum (a, b) {
    return a + b;
}
let proxy5 = new Proxy(sum, twice);

console.log(proxy5(1.3));  / / 8
console.log(proxy5.apply(null[1.3])); / / 8
Copy the code

Alternatively, calling reflect. apply directly will also be intercepted.

Reflect.apply(proxy5, null[9.10]) / / 38
Copy the code

has()

The has() method is used to intercept the HasProperty operation, which takes effect when determining whether an object has a property. A typical operation is the IN operator.

The has() method can take two parameters, the target object and the name of the property to be queried.

The following example uses the HAS method to hide some attributes from the IN operator.

let stu1 = {name: 'Joe'.score: 59};
let stu2 = {name: 'bill'.score: 99};

let handler = {
  has(target, prop) {
    if (prop === 'score' && target[prop] < 60) {
      console.log(`${target.name}Fail `);
      return false;
    }
    return prop intarget; }}let oproxy1 = new Proxy(stu1, handler);
let oproxy2 = new Proxy(stu2, handler);

'score' in oproxy1
// Zhang SAN failed
// false

'score' in oproxy2
// true

for (let a in oproxy1) {
  console.log(oproxy1[a]);
}
/ / zhang SAN
/ / 59

for (let b in oproxy2) {
  console.log(oproxy2[b]);
}
/ / li si
/ / 99
Copy the code

In the code above, the HAS intercept works only for the IN operator, for… The in loop does not work, resulting in unqualified attributes not being for… Excluded by the in loop.

Interception operations supported by Proxy

Proxy supports 13 types of interception operations.

get(target, propKey, receiver)

Intercepts reading of object properties, such as:

  • proxy.foo
  • proxy['foo'].

set(target, propKey, value, receiver)

Intercepting object property Settings, such as proxy.foo = v or proxy[‘foo’] = v, return a Boolean value.

has(target, propKey)

Intercepts the propKey in proxy operation, returning a Boolean value.

deleteProperty(target, propKey)

Intercepts the delete Proxy [propKey] operation, returning a Boolean value.

ownKeys(target)

Interception:

  • Object.getOwnPropertyNames(proxy)
  • Object.getOwnPropertySymbols(proxy)
  • Object.keys(proxy)
  • for... incycle

All of the above intercepts return an array.

This method returns the property names of all of the target Object’s own properties, whereas object.keys () returns only the traversable properties of the target Object itself.

getOwnPropertyDescriptor(target, propKey)

Interception Object. GetOwnPropertyDescriptor (proxy, propKey), returns the attributes describe objects.

defineProperty(target, propKey, propDesc)

Interception:

  • Object. DefineProperty (proxy, propKey propDesc)
  • Object.defineProperties(proxy, propDescs)

Returns a Boolean value.

preventExtensions(target)

Intercepting Object.preventExtensions(proxy) returns a Boolean value.

getPrototypeOf(target)

Intercepts Object.getProtoTypeof (proxy) to return an Object.

isExtensible(target)

Intercepting Object.isextensible (proxy), returning a Boolean value.

setPrototypeOf(target, proto)

Intercepts Object.setProtoTypeof (proxy, proto), returning a Boolean value.

If the target object is a function, there are two additional operations that can be intercepted.

apply(target, object, args)

Intercepting the actions of Proxy instances as function calls, such as:

  • proxy(... args)
  • proxy.call(object, ... args)
  • proxy.apply(...).

construct(target, args)

Intercepts operations called by Proxy instances as constructors, such as: new Proxy (… The args).

~

Thanks for reading!

~

Learn interesting knowledge, meet interesting friends, shape interesting soul!

Hello everyone, I am the author of “programming Samadhi”, I am king Yi, my public account is “programming Samadhi”, welcome to pay attention, I hope you can give me more advice!