ES6 in Action: How to Use Proxies
In computing terms, proxies sit between you and the things you’re communicating with. The term is most often applied to a proxy server — a device between the web browser (Chrome, Firefox, Safari, Edge etc.) and the web server (Apache, Nginx, IIS etc.) where a page is located. The proxy server can modify requests and responses. For example, it can increase efficiency by caching regularly accessed assets and serving them to multiple users.
ES6 proxies sit between your code and an object. A proxy allows you to perform meta-programming operations such as intercepting a call to inspect or change an object’s property.
The following terminology is used in relation to ES6 proxies:
target
The original object the proxy will virtualize. This could be a JavaScript object such as the jQuery library or native objects such as arrays or even another proxies.
handler
An object which implements the proxy’s behavior using…
traps
Functions defined in the handler which provide access to the target when specific properties or methods are called.
It’s best explained with a simple example. We’ll create a target object named target
which has three properties:
const target = {
a: 1,
b: 2,
c: 3
};
We’ll now create a handler object which intercepts all get
operations. This returns the target’s property when it’s available or 42 otherwise:
const handler = {
get: function(target, name) {
return (
name in target ? target[name] : 42
);
}
};
We now create a new Proxy by passing the target and handler objects. Our code can interact with the proxy rather than accessing the target
object directly:
const proxy = new Proxy(target, handler);
console.log(proxy.a); // 1
console.log(proxy.b); // 2
console.log(proxy.c); // 3
console.log(proxy.meaningOfLife); // 42
Let’s expand the proxy handler further so it only permits single-character properties from a
to z
to be set:
const handler = {
get: function(target, name) {
return (name in target ? target[name] : 42);
},
set: function(target, prop, value) {
if (prop.length == 1 && prop >= 'a' && prop <= 'z') {
target[prop] = value;
return true;
}
else {
throw new ReferenceError(prop + ' cannot be set');
return false;
}
}
};
const proxy = new Proxy(target, handler);
proxy.a = 10;
proxy.b = 20;
proxy.ABC = 30;
// Exception: ReferenceError: ABC cannot be set
Proxy Trap Types
We’ve seen the get
and set
in action which are likely to be the most useful traps. However, there are several other trap types you can use to supplement proxy handler code:
- construct(target, argList)
Traps the creation of a new object with thenew
operator. - get(target, property)
TrapsObject.get()
and must return the property’s value. - set(target, property, value)
TrapsObject.set()
and must set the property value. Returntrue
if successful. In strict mode, returningfalse
will throw a TypeError exception. - deleteProperty(target, property)
Traps adelete
operation on an object’s property. Must return eithertrue
orfalse
. - apply(target, thisArg, argList)
Traps object function calls. - has(target, property)
Trapsin
operators and must return eithertrue
orfalse
. - ownKeys(target)
TrapsObject.getOwnPropertyNames()
and must return an enumerable object. - getPrototypeOf(target)
TrapsObject.getPrototypeOf()
and must return the prototype’s object or null. - setPrototypeOf(target, prototype)
TrapsObject.setPrototypeOf()
to set the prototype object. No value is returned. - isExtensible(target)
TrapsObject.isExtensible()
, which determines whether an object can have new properties added. Must return eithertrue
orfalse
. - preventExtensions(target)
TrapsObject.preventExtensions()
, which prevents new properties from being added to an object. Must return eithertrue
orfalse
. - getOwnPropertyDescriptor(target, property)
TrapsObject.getOwnPropertyDescriptor()
, which returns undefined or a property descriptor object with attributes forvalue
,writable
,get
,set
,configurable
andenumerable
. - defineProperty(target, property, descriptor)
TrapsObject.defineProperty()
which defines or modifies an object property. Must returntrue
if the target property was successfully defined orfalse
if not.
Proxy Example 1: Profiling
Proxies allow you to create generic wrappers for any object without having to change the code within the target objects themselves.
In this example, we’ll create a profiling proxy which counts the number of times a property is accessed. First, we require a makeProfiler
factory function which returns the Proxy
object and retains the count state:
// create a profiling Proxy
function makeProfiler(target) {
const
count = {},
handler = {
get: function(target, name) {
if (name in target) {
count[name] = (count[name] || 0) + 1;
return target[name];
}
}
};
return {
proxy: new Proxy(target, handler),
count: count
}
};
We can now apply this proxy wrapper to any object or another proxy. For example:
const myObject = {
h: 'Hello',
w: 'World'
};
// create a myObject proxy
const pObj = makeProfiler(myObject);
// access properties
console.log(pObj.proxy.h); // Hello
console.log(pObj.proxy.h); // Hello
console.log(pObj.proxy.w); // World
console.log(pObj.count.h); // 2
console.log(pObj.count.w); // 1
While this is a trivial example, imagine the effort involved if you had to perform property access counts in several different objects without using proxies.
Proxy Example 2: Two-way Data Binding
Data binding synchronizes objects. It’s typically used in JavaScript MVC libraries to update an internal object when the DOM changes and vice versa.
Presume we have an input field with an ID of inputname
:
<input type="text" id="inputname" value="" />
We also have a JavaScript object named myUser
with an id
property which references this input:
// internal state for #inputname field
const myUser = {
id: 'inputname',
name: ''
};
Our first objective is to update myUser.name
when a user changes the input value. This can be achieved with an onchange
event handler on the field:
inputChange(myUser);
// bind input to object
function inputChange(myObject) {
if (!myObject || !myObject.id) return;
const input = document.getElementById(myObject.id);
input.addEventListener('onchange', function(e) {
myObject.name = input.value;
});
}
Our next objective is to update the input field when we modify myUser.name
within JavaScript code. This is not as simple, but proxies offer a solution:
// proxy handler
const inputHandler = {
set: function(target, prop, newValue) {
if (prop == 'name' && target.id) {
// update object property
target[prop] = newValue;
// update input field value
document.getElementById(target.id).value = newValue;
return true;
}
else return false;
}
}
// create proxy
const myUserProxy = new Proxy(myUser, inputHandler);
// set a new name
myUserProxy.name = 'Craig';
console.log(myUserProxy.name); // Craig
console.log(document.getElementById('inputname').value); // Craig
This may not be the most efficient data-binding option, but proxies allow you to alter the behavior of many existing objects without changing their code.
Further Examples
Hemanth.HM’s article Negative Array Index in JavaScript suggests using proxies to implement negative array indexes. For example, arr[-1]
returns the last element, arr[-2]
returns the second-to-last element, and so on.
Nicholas C. Zakas’ article Creating type-safe properties with ECMAScript 6 proxies illustrates how proxies can be used to implement type safety by validating new values. In the example above, we could verify myUserProxy.name
was always set to a string and throw an error otherwise.
Proxy Support
The power of proxies may not be immediately obvious, but they offer powerful meta-programming opportunities. Brendan Eich, the creator of JavaScript, thinks Proxies are Awesome!
Currently, proxy support is implemented in Node and all current browsers, with the exception of Internet Explorer 11. However, please note that not all browsers support all traps. You can get a better idea of what’s supported by consulting this browser compatibility table on the MDN Proxy page.
Unfortunately, it’s not possible to polyfill or transpile ES6 proxy code using tools such as Babel, because proxies are powerful and have no ES5 equivalent.