Solution Review: Proxy
Let's discuss the solution to the Proxy challenge given in the previous lesson.
We'll cover the following...
Solution
Let’s take a look at the solution code.
Press + to interact
'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 Tennisconsole.log(proxy.playFootball()); //I love to play Footballconsole.log(proxy.playPolitics()); //I don't play Politicstry {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 ...