Proxies
Learn how to define custom behaviors for fundamental operations with Proxies.
We'll cover the following...
What is a Proxy?
From MDN:
The Proxy object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).
How to use a Proxy ?
This is how we create a Proxy:
var x = new Proxy(target,handler)
- our
targetcan be anything, from an object, to a function, to anotherProxy - a
handleris an object which will define the behavior of ourProxywhen an operation is performed on it
Node.js
// our objectconst dog = { breed: "German Shephard", age: 5}// our Proxyconst dogProxy = new Proxy(dog, {get(target,breed){return target[breed].toUpperCase();},set(target, breed, value){console.log("changing breed to...");target[breed] = value;}});console.log(dogProxy.breed);// "GERMAN SHEPHARD"console.log(dogProxy.breed = "Labrador")// changing breed to...// "Labrador"console.log(dogProxy.breed);// "LABRADOR"
When we call the get method, we step inside the normal flow and ...
Ask