Search⌘ K
AI Features

Solution Review: Proxy

Explore how to create and use a Proxy in JavaScript to modify object behavior dynamically. Learn to implement traps using the get handler, manage property access, and handle errors effectively within metaprogramming.

We'll cover the following...

Solution

Let’s take a look at the solution code.

Node.js
'use strict';
const createPlayMethodProxy = function(instance) {
const handler = {
get: function(target, propertyName, receiver) {
if(propertyName.startsWith('play')) {
const activity = propertyName.substring(4);
if(target.activities.includes(activity)) {
return () => `I love to play ${activity}`;
} else {
return () => `I don't play ${activity}`;
}
} else {
throw new Error(`${propertyName} is not a function`);
}
}
};
return new Proxy(instance, handler);
};
const proxy = createPlayMethodProxy({ activities: ['Football', 'Tennis'] });
console.log(proxy.playTennis()); //I love to play Tennis
console.log(proxy.playFootball()); //I love to play Football
console.log(proxy.playPolitics()); //I don't play Politics
try {
console.log(proxy.dance());
} catch(ex) {
console.log(ex.message); //dance is not a function
}

Explanation

In this challenge, we were required to create and return a proxy from the function createPlayMethodProxy().

So, let’s start by creating the ...