Detailed explanation of JavaScript Proxy object

Detailed explanation of JavaScript Proxy object

1. What is Proxy?

The Proxy object is used to intercept and modify specified operations of the target object.

// Syntax const p = new Proxy(target, handler)
  • target : The target object (can be any type of object, including a native array, a function, or even another proxy).
  • handler: An object with functions as attributes to implement interception and custom operations.

2. How to use it?

1. Simple example of using Proxy

Accessing a non-existent property, set the default value to return instead of undefined

// 1. Find a suitable handler and write code const handler = {
    get: function(obj, prop) {
        return prop in obj ? obj[prop] : 37;
    }
};
// 2. Create a new Proxy object const p = new Proxy({}, handler);
// 3. Execute operation pa = 1;
pb = undefined;
// 4. Check the results console.log(pa, pb); // 1, undefined
console.log('c' in p, pc); // false, 37

2. The target object is modified correctly

let target = {};
let p = new Proxy(target, {});
pa = 37; // The operation is forwarded to the target console.log(target.a); // 37. The operation has been forwarded correctly

3. Use set handler for data validation

let validator = {
  set: function(obj, prop, value) {
    if (prop === 'age') {
      if (!Number.isInteger(value)) {
        throw new TypeError('The age is not an integer');
      }
      if (value > 200) {
        throw new RangeError('The age seems invalid');
      }
    }
    // The default behavior to store the value
    obj[prop] = value;
    // Indicates success return true;
  }
};
let person = new Proxy({}, validator);
person.age = 100;
console.log(person.age);
// 100
person.age = 'young';
// Throws an exception: Uncaught TypeError: The age is not an integer
person.age = 300;
// Throws an exception: Uncaught RangeError: The age seems invalid

4. Extended Constructor

function extend(sup, base) {
  var descriptor = Object.getOwnPropertyDescriptor(
    base.prototype, "constructor"
  );
  base.prototype = Object.create(sup.prototype);
  var handler = {
    construct: function(target, args) {
      var obj = Object.create(base.prototype);
      this.apply(target, obj, args);
      return obj;
    },
    apply: function(target, that, args) {
      sup.apply(that, args);
      base.apply(that, args);
    }
  };
  var proxy = new Proxy(base, handler);
  descriptor.value = proxy;
  Object.defineProperty(base.prototype, "constructor", descriptor);
  return proxy;
}
var Person = function (name) {
  this.name = name
};
var Boy = extend(Person, function (name, age) {
  this.age = age;
});
Boy.prototype.sex = "M";
var Peter = new Boy("Peter", 13);
console.log(Peter.sex); // "M"
console.log(Peter.name); // "Peter"
console.log(Peter.age); // 13

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Proxy Object in JavaScript
  • Detailed explanation of the principle of js Proxy
  • JS takes you deep into the world of Proxy
  • Specific use of ES6 Proxy in JavaScript
  • What interesting things can JavaScript Proxy do?

<<:  Font references and transition effects outside the system

>>:  Introduction to encryption of grub boot program in Linux

Recommend

Practical MySQL + PostgreSQL batch insert update insertOrUpdate

Table of contents 1. Baidu Encyclopedia 1. MySQL ...

MySQL table name case selection

Table of contents 1. Parameters that determine ca...

Implementation of a simple login page for WeChat applet (with source code)

Table of contents 1. Picture above 2. User does n...

Summary of common functions and usage methods of WeChat applet development

Here, I have mainly sorted out some commonly used...

Web data storage: Cookie, UserData, SessionStorage, WebSqlDatabase

Cookie It is a standard way to save the state of ...

Example of using MySQL to count the number of different values ​​in a column

Preface The requirement implemented in this artic...

Comparative Analysis of UI Applications of Image Social Networking Sites (Figure)

In our life, work and study, social networks have ...

Solve the Docker x509 insecure registry problem

After installing Docker, I encountered the x509 p...

Using CSS3 to achieve transition and animation effects

Why should we use CSS animation to replace JS ani...

Basic commands for MySQL database operations

1. Create a database: create data data _name; Two...

How to upgrade CentOS7 to CentOS8 (detailed steps)

This article uses a specific example to introduce...

Understanding the Lazy Loading Attribute Pattern in JavaScript

Traditionally, developers create properties in Ja...