Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Today is the first day of the National Day holiday. I wish you all a happy National Day. Today, WE will look at the use of JavaScript Proxy.

Proxy Example

The get ()

When the target object is accessed by proxy, the get() function is triggered.

In the previous example, printing the properties of the proxyUser object prints an additional message.

So we can develop our own custom logic in the get() function.

For example, use get() to implement a function that evaluates a property. This is similar to computed properties in Vue.

const user = {
    firstName: 'the little handsome'.lastName: 'Programming Notes'
}

const handler = {
    get(target, property) {
        return property === 'fullName' ?
            `${target.firstName} ${target.lastName}`: target[property]; }};const proxyUser = new Proxy(user, handler);

console.log(proxyUser.fullName);
// Output: Xiaoshuai programming notes
Copy the code

The above user object does not have a fullName attribute. We use a custom judgment in get() to return a combination of the firstName and lastName attributes.

Set () intercept

The set() function is fired when we want to assign a value to the proxy object property.

If we have a requirement to ensure that the age attribute has a numeric type and is 18 years or older, we can customize the logic with the set() function.

const user = {
    firstName: 'the little handsome'.lastName: 'Programming Notes'.age: 20
}

const handler = {
    set(target, property, value) {
        if (property === 'age') {
            if (typeofvalue ! = ='number') {
                throw new Error('Please enter the correct age');
            }
            if (value < 18) {
                throw new Error('You must be 18 years of age') } } target[property] = value; }};const proxyUser = new Proxy(user, handler);
Copy the code

Then, try to set a value of the wrong type

proxyUser.age = 'foo';
// Output: Uncaught Error: Please enter the correct age
Copy the code

Then try to set a value less than 18

proxyUser.age = 16;
// Output: Uncaught Error: Your age must be 18
Copy the code

And then finally set the correct value

proxyUser.age = 23;
// Output: 23
console.log(proxyUser);
// output: Proxy {firstName: '小 shuai ', lastName: 'programming note ', age: 23}
console.log(user);
// {firstName: '小 shuai ', lastName: 'programming notes ', age: 23}
Copy the code

The apply () intercept

Apply () is used to intercept functions when calling them and do some other custom logic.

const user = {
    firstName: 'hello'.lastName: 'world'
}

const getFullName = function (user) {
    return `${user.firstName} ${user.lastName}`;
}

const getFullNameProxy = new Proxy(getFullName, {
    apply(target, thisArg, args) {
      	// target is the target function getFullName
      	console.log(target);
      	// args is the argument user passed in when the function is actually called
      	console.log(args);
        return target(...args).toUpperCase();
    }
});

console.log(getFullNameProxy(user));
// Output: HELLO WORLD
Copy the code

I created a function proxy getFullNameProxy to convert the value to uppercase at the end of the function call and return it.

The last

There are many other operations that can be intercepted by proxy. The three above, get(), set() and apply(), are commonly used.

There are other, less popular, less used ones

  • constructIntercept –newA call
  • getPrototypeOf– Intercepting proxy[[GetPrototypeOf]]
  • setPrototypeOf– Intercepting proxyObject.setPrototypeOf
  • isExtensible– Intercepting proxyObject.isExtensible
  • preventExtensions– Intercepting proxyObject.preventExtensions
  • getOwnPropertyDescriptor– Intercepting proxyObject.getOwnPropertyDescriptor

Here today, happy National Day.

Welcome to pay attention to my public number [xiaoshuai’s programming notes], follow me a little bit of progress every day