Home > Article > Web Front-end > Detailed introduction to Proxy in JavaScript (code example)
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, { // ... })
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() |
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
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:
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:
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".
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);
Ș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
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
‗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]
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
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!