Search⌘ K
AI Features

Leasing an Object Using a Revocable Proxy

Explore how to create revocable proxies in JavaScript to lease objects with limited lifetimes. Understand the use of Proxy.revocable to return a proxy and a revoke function, enabling dynamic control over object access. Learn to handle revocation scenarios and improve code clarity through destructuring techniques.

You’ve learned to create proxies and write traps; let’s move on to applying this knowledge. Our target is method synthesis, but let’s explore one other benefit of proxies: the ability to lease an object.

Suppose we want to limit the lifetime of an object. A function that creates an object with new may use it as long as it wants, as long as the instance reference is in the scope. If you want to return an object to a caller but withdraw or revoke access to that object either after some time or when some condition is met, use a revocable proxy.

Creating a revocable proxy

Here’s a counterFactory() function that creates an instance of a Counter class but returns a revocable proxy instead of the original object.

Node.js
'use strict';
//START:REVOCABLE
const counterFactory = function() {
class Counter {
constructor() { this.value = 0; }
increment() { this.value += 1; }
get count() { return this.value; }
}
//START:CLUTTER
const { proxy: counterProxy, revoke: revokeFunction } =
Proxy.revocable(new Counter(), {});
//END:CLUTTER
const leaseTime = 100;
setTimeout(revokeFunction, leaseTime);
return counterProxy;
};
//END:REVOCABLE

Under the hood

  • In the function, instead of using new Proxy(), we used Proxy.revocable() to create a proxy. ...