Saturday, October 5, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Proxy revocable() Method

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.

  • 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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments