Table of Contents
has
get
set
apply
construct
Create a revocable Proxy object
Home Web Front-end JS Tutorial Detailed introduction to Proxy in JavaScript (code example)

Detailed introduction to Proxy in JavaScript (code example)

Dec 10, 2018 pm 05:52 PM
javascript

This article brings you a detailed introduction (code example) about Proxy in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Proxy allows us to monitor and interfere with most behaviors of any object and achieve more customized program behaviors.

Usage: new Proxy(target, handler).

Proxy captures the program's behavior on the corresponding object by setting a behavior monitoring method.

    const obj = {};
    const proxy = new Proxy(obj, {
        // ...
    })
Copy after login

The constructor of Proxy accepts two parameters. The first parameter is the target object that needs to be packaged. The second parameter is the listener used to monitor the behavior of the target object. The listener can accept some Parameters to monitor the corresponding program behavior.
Monitoring properties, parameters and monitoring content

Attribute value Listener parameters Monitoring content
has (target, prop) Use of monitoring in statement
get (target, prop, reciver) Listen to the property reading of the target object
set (target, prop, value, reciver) Listen to the property assignment of the target object
deleteProperty (target, prop) Listen to the delete statement on the target object Deletion property behavior
ownKeys (target) Listen to the reading of Object.getOwnPropertyName()
apply (target, thisArg, arguments) Listen to the calling behavior of the target function (as the target object)
construct (target, arguments, newTarget) Listen to the behavior of the target constructor (as the target object) using new to generate an instance
getPrototypeOf (target) Listen to the reading of Objext.getPrototypeOf()
setPrototypeOf (target, prototype) Listen The call of Objext.setPrototypeOf()
isExtensible (target) Monitor the reading of Objext.isExtensible()
preventExtensions (target) Listen to the reading of Objext.preventExtensions()
getOwnPropertyDescriptor (target, prop) Listen to the call of Objext.getOwnPropertyDescriptor()
defineProperty (target, property, descriptor) Listen to the call of Object.defineProperty()

has

You can define the has listening method for the Proxy handler to check the listening program through the in statement The procedure of whether a string or number is the property key of a property in the Proxy's target object.

const p = new Proxy({}, {
    has(target, prop){
        console.log(`Checking "${prop}" is in the target or not`);
        return true;
    }
})

console.log('foo' in p);
// Checking "foo" is in the target or not
// true
Copy after login

There are two things to note about this listening method. If these two situations are encountered, a TypeError will be thrown.

1. When the target object is disabled by other programs through Object.preventExtensions() (the object cannot add new attributes, it can only operate on the currently existing attributes, including reading and operating) and delete, but once deleted, it cannot be redefined) function, and the property key being checked does exist in the target object, the listening method cannot return false.

const obj = {foo: 1};

Object.preventExtensions(obj);

const p = new Proxy(obj, {
    has(target, prop){
        console.log(`Checking "${prop}" is in the target or not`);
        return false; 
    }
})

console.log('foo' in p);   
//抛出Uncaught TypeError:
Copy after login

2. When the property key being checked exists in the target object and the configurable configuration of the property is false, the listening method cannot return false.

const obj = {};

Object.defineProperty(obj, 'foo', {
    configurable: false,
    value: 10
})

const p = new Proxy(obj, {
    has(target, prop){
        console.log(`Checking "${prop}" is in the target or not`);
        return false;
    }
})

console.log('foo' in p);
//抛出Uncaught TypeError:
Copy after login

get

Getter can only monitor known property keys, but cannot intercept all property reading behaviors, while Proxy can intercept and interfere by setting the get listening method. All properties of the target object are read.

const obj = {foo: 1};
const p = new Proxy(obj, {
    get(target, prop){
        console.log(`Program is trying to fetch the property "${prop}".`);
        return target[prop];
    }
})

alert(p.foo);  // Program is trying to fetch the property "foo".
alert(p.something);    // Program is trying to fetch the property "something".
Copy after login

This listening method also has something to pay attention to - when the configurable and writable properties of the target object's read properties are both false, the final value returned by the listening method must be consistent with the original property value of the target object. .

const obj = {};

Object.defineProperty(obj, 'foo', {
    configurable: false,
    value: 10,
    writable: false
})

const p = new Proxy(obj, {
    get(target, prop){
        return 20;
    }
})

console.log(p.foo);
Copy after login

set

Șhandler.set is used to monitor all property assignment behaviors of the target object. Note that if a property of the target object itself is not writable or configurable, set must not change the value of this property and can only return the same value, otherwise an error will be reported.

const obj = {};
const p = new Proxy(obj, {
    set(target, prop, value){
        console.log(`Setting value "${value}" on the key "${prop}" in the target object`);
        target[prop] = value;
        return true;
    }
})

p.foo = 1;  
// Setting value "1" on the key "foo" in the target object
Copy after login

apply

handler.apply , Proxy also provides attributes for monitoring its calling behavior for the function as the target object.

const sum = function(...args) {
  return args
    .map(Number)
    .filter(Boolean)
    .reduce((a, b) => a + b);

}

const p = new Proxy(sum, {
  apply(target, thisArg, args) {
    console.log(`Function is being called with arguments [${args.join()}] and context ${thisArg}`);
    return target.call(thisArg, ...args);
  }
})

console.log(p(1, 2, 3));
// Function is being called with arguments [1,2,3] and context undefined
// 6
Copy after login

construct

‗handler.construct, Proxy can also use the class as the target listening object and monitor its behavior of producing new instances through the new statement. This can also be used as a constructor. on the constructor.

class Foo{};

const p = new Proxy(Foo, {
    construct(target, args, newTarget){
        return {arguments: args}    // 这里返回的结果会是 new 所得到的实例
    }
});

const obj = new p(1, 2, 3);
console.log(obj.arguments);  // [1, 2, 3]
Copy after login

Create a revocable Proxy object

Usage: Proxy.revocable(target, handler): (proxy, revoke).

const obj = {foo: 10};
const revocable = Proxy.revocable(obj, {
    get(target, prop){
        return 20;
    }
})
const proxy = revocable.proxy;
console.log(proxy.foo); // 20
revocable.revoke();
console.log(proxy.foo); 
// TypeError: Cannot perform 'get' on a proxy that has been revoked
Copy after login

Proxy.revocable(target, handler) will return an object with two attributes. One of the proxy is the revocable Proxy object generated by the function, and the other revoke is the revocable Proxy object generated by the function. Dismissal method of Proxy object.

The above is the detailed content of Detailed introduction to Proxy in JavaScript (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles