JavaScript Proxy
Damon Marc Rocha II
Posted on October 26, 2020
I decided to take a break from the bash blogs I have been writing to cover something I recently discovered while traversing through the world of JavaScript, Proxies.
What Are Proxies
A JavaScript Proxy is an object that wraps around another object and intercepts/redefines any operation on it. So in other words, A proxy watches what happens to an object and conducts methods defined by the programmer. To create a proxy you need an object and a handler function. An example is shown below
Example:
const proxy1 = new Proxy(target, handler)
The target is the object you are trying to control using the handler you define. A handler usually falls into four categories: lookup, assignment, enumeration, and function invocations. These functions can implement methods called traps. In this article, I will cover get() and set().
get() Example:
const user = {
firstName: 'John',
lastName: 'Doe',
email: 'john.doe@example.com',
}
const handler = {
get(target, property) {
return property === 'fullName' ?
`${target.firstName} ${target.lastName}` :
target[property];
}
};
let proxy = new Proxy(target, handler);
console.log(proxy.fullName) //=> John Doe
The get trap is called when an object is accessed via the proxy item. It takes in the object and property that is being called and then returns various types of information; even that which was not originally stored in the object (e.g fullName).
set() Example:
The set trap controls behavior on the object when a property is changed.
const triangle = {
base: 100,
height: 50,
}
const handler = {
get: function (target, property){
if(property === 'area'){
return 0.5*target.base*target.height
}
return target[property]
},
set: function (target, property, value) {
if (typeof value !== 'number') {
throw new Error(`${property} must be a number.`);
}
if (value < 0) {
throw new Error(`The ${property} must be 18 or older.`)
}
}
target[property] = value;
}
};
const proxyUser = new Proxy(triangle, handler);
Other Traps
- apply()
- construct
- getPrototypeOf
- setPrototypeOf
- isExtensible
- preventExtensions
- getOwnPropertyDescriptor
Now I know a lot of this can be created via classes now, but I know there are some places where a lightweight customizable Proxy would be a great option. If you agree with this then here is another resource.
Thanks for reading and it's back to bash next week. See you then.
Posted on October 26, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.