Open In App

JavaScript Proxy revocable() Method

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.

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.




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.




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:

We have a complete list of JavaScript Proxy methods, to check Please go through the JavaScript Proxy Reference article.


Article Tags :