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

Problems and experiences encountered in web development

<br />The following are the problems I encou...

How to quickly insert 10 million records into MySQL

I heard that there is an interview question: How ...

Zen HTML Elements Friends who use zen coding can collect it

html ¶ <html></html> html:xml ¶ <h...

Detailed explanation of Truncate usage in MYSQL

This article guide: There are two ways to delete ...

Implementing custom radio and check box functions with pure CSS

1. Achieve the effect 2 Knowledge Points 2.1 <...

Analysis of the advantages and disadvantages of MySQL stored procedures

MySQL version 5.0 began to support stored procedu...

Vue login function implementation

Table of contents Written in front Login Overview...

How to get/calculate the offset of a page element using JavaScript

question By clicking a control, a floating layer ...

Detailed explanation of common template commands in docker-compose.yml files

Note: When writing the docker-compose.yml file, a...

Detailed usage of MYSQL row_number() and over() functions

Syntax format: row_number() over(partition by gro...

Understanding MySQL Locking Based on Update SQL Statements

Preface MySQL database lock is an important means...

How to import, register and use components in batches in Vue

Preface Components are something we use very ofte...

How to use http and WebSocket in CocosCreator

Table of contents 1. HttpGET 2. HTTP POST WebSock...

Vue+element+oss realizes front-end fragment upload and breakpoint resume

Pure front-end implementation:切片上傳斷點續傳.斷點續傳needs ...

CentOS 6.5 installation mysql5.7 tutorial

1. New Features MySQL 5.7 is an exciting mileston...