In Depth Javascript 2: Proxy Object to Limit an Object’s lifespan

Mipsmonsta
3 min readDec 11, 2020

Advance meta-programming

In our last article on Proxy Object, we saw the basics of setting up the Proxy Object with a target and handler. We touched on how the proxy can intercept the calls to the target and with the get function defined in the handler, so that you can manipulate or simply spy (and logged) the calls. We will know focus on a more advance usecase of the Proxy Object, that is, how to limit the “useful” lifespan of a target object.

In the diagrams above, the calls to the target object will produce useful outputs, but after a defined period of time, the same calls will produce errors. Effectively, the target object has a limited lease life. To achieve this, we can make use of Proxy object.

Creating a Fortune Cookie that Expires…

Enough theory. Let’s look at a concrete example. Supposed we have a fortune cookie, which will output a wise wisdom every time you call it. Let’s see how the code will look like below.

So every time you call the saying property of cookie, you get

Life is a highway, you will ride it!

How soothing? What if we want to stop the cookie from sprouting the wise sayings after 3 seconds. Well. We will create a proxy object as such:

The code is using a factory pattern to create the proxy. Notice the use of the static constructor method of Proxy.revocable(target, handler). The static method will return a Proxy object and a revoke function. A timeout is set such that after a leased time in milliseconds, the revoke function is invoke. The proxy object is in tandem at after the setting of the timeout to be return by the factor.

Now we use the proxy.

In the above code, we obtain the proxy from the factory method. Then immediately, we ask for the wise saying, this time not from the fortune cookie, but from the proxy instead. Then after 5 seconds or 5000 milliseconds, we check with the fortune cookie and again ask for a saying. We do not expect to be successful in obtaining a saying at the 5 seconds mark. Are we successful?

Time wait for no man, woman.After some time ...TypeError: Cannot perform 'get' on a proxy that has been revoked
at Timeout.setTimeout [as _onTimeout] (/home/pi/Documents/nodeprojs/learn_promises/src/exercises/ch12_more_metaprogramming.js:226:25)
at ontimeout (timers.js:436:11)
at tryOnTimeout (timers.js:300:5)
at listOnTimeout (timers.js:263:5)
at Timer.processTimers (timers.js:223:10)

Looking at the output! An affirmative YES!

You should now be able to write codes that work for a defined amount of time, and after fails! Please see the full code, and tinker with it. Hope you like this article. Happy coding!

--

--

Mipsmonsta

Writing to soothe the soul, programming to achieve flow