Search⌘ K

Solution Review: Revocable Proxy

Learn how to implement a revocable proxy in JavaScript by creating a handler with a get trap and using Reflect to access object properties. Understand the mechanism of revoking proxy functionality after a set lease period, enhancing control over dynamic object behavior in metaprogramming.

We'll cover the following...

Solution

Look at how the code given below solves the challenge.

Node.js
'use strict';
const createRevocableProxy = function(instance) {
const handler = {
get: function(target, propertyName , receiver) {
return Reflect.get(target, propertyName).bind(target);
}
};
const { proxy, revoke } = Proxy.revocable(instance, handler);
setTimeout(revoke, 3000);
return proxy;
};
const proxy = createRevocableProxy(new Date());
const callGetYear = function() {
try {
console.log(1900 + proxy.getYear());
} catch(ex) {
console.log(ex.message);
}
};
callGetYear(); //current year like 2018
setTimeout(callGetYear, 1000);
setTimeout(callGetYear, 5000);
//Cannot perform 'get' on a proxy that has been revoked

Explanation

Now, let’s dig into the above code.

Rember you were asked to create and return a proxy from the function createRevocableProxy().

handler

First of all, we create a handlerHandler to ...