Javascript - Collection Revocable Proxy

Introduction

ES6 can create proxies that can be revoked.

Proxy.revocable() method is used to create a revocable proxy object.

It takes a handler and a target object and returns a newly created revocable proxy object.

A revocable proxy object has two properties: proxy and revoke.

const { proxy, revoke } = Proxy.revocable(target, handler); 

where,

  • proxy - A Proxy object created with new Proxy (target, handler) call
  • revoke - A function with no argument to invalidate (switch off) the proxy.

If the revoke() function gets called, the proxy becomes unusable.

Any trap to a handler will throw a TypeError.

Once a proxy is revoked, it will remain revoked and can be garbage collected.

Subsequent calls of revoke have no further effect.

Demo

const restaurant = { 
    soda: 10, //from  ww  w  .ja v a  2s  .  co m
    beer: 5 
}; 

const { proxy, revoke } = Proxy.revocable(restaurant, {}); 

console.log(proxy.soda);   // 10 
console.log(proxy.beer);   // 5 

revoke(); 

console.log(proxy.soda);   // TypeError: Revoked

Result

Revocable Proxy can be useful to enhance the security of an object where if attempts to access a private property has been made, the proxy can be revoked.

We can modify the above example to enhance the privacy of beer property as follows:

Demo

const restaurant = { 
    soda: 10, //from   w  ww. j a  v a2s. co  m
    beer: 5 
}; 

const resthandler = { 
    get: function(target, property) { 
        if (property === "beer") { 
            revoke(); 
            return undefined; 
        } 
        return target[property]; 
    } 
} 
const { proxy, revoke } = Proxy.revocable(restaurant, resthandler); 

console.log(proxy.soda);    // 10 
console.log(proxy.beer);    // undefined 
console.log(proxy.soda);    // TypeError: Revoked

Result

Here, we are returning undefined and revoking the proxy if beer property is accessed, cutting off further calls to the target object via proxy.

Related Topic