The Proxy.revocable() method is a built-in method in JavaScript that creates a revocable Proxy object. This method returns an object that contains two properties: proxy and revoke.
The proxy property is a Proxy object, which is used to intercept and handle operations on another object. The revoke property is a function that can be called to revoke the Proxy, which means that any further operation on the proxy object will throw a TypeError.
Here’s an example of how to use the Proxy.revocable() method:
Syntax:
Proxy.revocable(tar, hand)
Parameters: This method accepts two parameters.
- tar: It is the object on which we want the proxy to be applied.
- hand: This object contains the logic function which defines how the proxy will operate on the target object.
Return Value: It returns a plain JavaScript object with two values where the first value is the proxy object and the second object is the revoke function to detach the proxy.
Example 1: This example will create a Proxy object which we can revoke.
Javascript
let details = { Â Â Â Â name: "Raj" , Â Â Â Â Course: "DSA" , } const {proxy, revoke} = Proxy.revocable(details, {}); Â
console.log(proxy.name); console.log(proxy.Course); Â
revoke(); Â
console.log(proxy.name); |
Output: We get an error if we try to access the Proxy object after it has been revoked
Â
Example 2: This example revokes a proxy based on a condition.
Javascript
let details = { Â Â Â Â name: "Raj" , Â Â Â Â Course: "DSA" , } const {proxy, revoke} = Proxy.revocable(details, { Â Â Â Â get: function (tar, prop){ Â Â Â Â Â Â Â Â if (prop == "Course" ){ Â Â Â Â Â Â Â Â Â Â Â Â revoke(); Â Â Â Â Â Â Â Â Â Â Â Â return undefined; Â Â Â Â Â Â Â Â } Â Â Â Â Â Â Â Â return tar[prop]; Â Â Â Â } }); Â
console.log(proxy.name); console.log(proxy.Course); console.log(proxy.name); |
Output: If we try to access the Course in the details the Proxy object gets revoked
Â
Supported Browsers:
- Chrome
- Edge
- Firefox
- Opera
- Safari
We have a complete list of JavaScript Proxy methods, to check Please go through the JavaScript Proxy Reference article.