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

How to convert Chinese into UTF-8 in HTML

In HTML, the Chinese phrase “學好好學” can be express...

JavaScript determines whether the browser is IE

As a front-end developer, I can’t avoid IE’s pitf...

AsyncHooks asynchronous life cycle in Node8

Async Hooks is a new feature of Node8. It provide...

Does the website's text still need to be designed?

Many people may ask, does the text on the website...

Detailed explanation of Vue's calculated properties

1. What is a calculated attribute? In plain words...

JavaScript type detection method example tutorial

Preface JavaScript is one of the widely used lang...

A brief discussion on creating cluster in nodejs

Table of contents cluster Cluster Details Events ...

Docker container introduction

1. Overview 1.1 Basic concepts: Docker is an open...

js to achieve waterfall flow layout (infinite loading)

This article example shares the specific code of ...

How to set the style of ordered and unordered list items in CSS

In an unordered list ul>li, the symbol of an u...

A brief introduction to Tomcat's overall structure

Tomcat is widely known as a web container. It has...

Example of stars for CSS rating effect

What? What star coat? Well, let’s look at the pic...