Introduction
Proxies are objects for which the programmer has to define the semantics in JavaScript. The default object semantics are implemented in the JavaScript engine, often written in lower-level languages like C++. Proxies let the programmer define most of the behavior of an object in JavaScript. They are said to provide a meta-programming API.
Note: The SpiderMonkey Proxy implementation is a prototype and the Proxy API and semantics specifications are unstable. The SpiderMonkey implementation may not reflect the latest specification draft. It is subject to change anytime. It is provided as an experimental feature. Do not rely on it for production code.
This page describes the new API (called 'direct_proxies') which is part of Firefox 18. For the previous API (Firefox 17 and below), visit the old proxy API page
Terminology
- catch-all mechanism (or "intercession API")
- The technical term for this feature.
- proxy
- The object whose accesses are being intercepted.
- handler
- Placeholder object which contains traps.
- traps
- The methods that provide property access. This is analogous to the concept of traps in operating systems.
- target
- Object which the proxy virtualizes. It is often used as storage backend for the proxy. Invariants regarding object non-extensibility or non-configurable properties are verified against the target.
Proxy API
Proxies are new objects; it's not possible to "proxyfy" an existing object. Here is how to create a proxy
var p = new Proxy(target, handler);
Where:
targetis an object (can be any sort of objects, including a native array, a function or even another proxy).handleris an object whose properties are functions which define the behavior of the proxy when an operation is performed on it.
Handler API
All traps are optional. If a trap has not been defined, the default behavior is to forward the operation to the target.
Note: Starting with Firefox 21, proxyfied arrays without the get trap are not working properly. If the get trap not defined, Array.length returns 0 and the set trap doesn't get called. A workaround is to add the get trap even if it's not necessary in your code. This issue has been fixed with Firefox 26. (bug 895223)
| JavaScript code | Handler method | Description |
|---|---|---|
Object.getOwnPropertyDescriptor(proxy, name) |
getOwnPropertyDescriptor |
Should return a valid property descriptor object, or undefined to indicate that no property named name exists in the emulated object. |
Object.getOwnPropertyNames(proxy) |
getOwnPropertyNames function(target) -> [String] |
Return an array of all own (non-inherited) property names of the emulated object. |
Object.defineProperty(proxy,name,pd) |
defineProperty function(target, name, propertyDescriptor) -> any |
Define a new property whose attributes are determined by the given propertyDescriptor. The return value of this method is ignored. |
delete proxy.name |
deleteProperty function(target, name) -> boolean |
Delete the named property from the proxy. The boolean return value of this method should indicate whether or not the name property was successfully deleted. |
Object.freeze(proxy) |
freeze function(target) -> boolean |
Freezes the object. The boolean indicates whether the operation was successful |
Object.seal(proxy) |
seal function(target) -> boolean |
Seals the object. The boolean indicates whether the operation was successful |
Object.preventExtensions(proxy) |
preventExtensions function(target) -> boolean |
Makes the object non-extensible. The boolean indicates whether the operation was successful |
name in proxy |
has function(target, name) -> boolean |
|
Object.prototype.hasOwnProperty.call(proxy, name) |
hasOwn function(target, name) -> boolean |
|
|
|
get function(target, name, receiver) -> any |
receiver is either the proxy or an object that inherits from the proxy. |
|
|
set function(target, name, val, receiver) -> boolean |
receiver is either the proxy or an object that inherits from the proxy. |
for(prop in proxy){...} |
enumerate function(target) -> [String] |
From the proxy user point of view, properties appear in the for..in loop in the same order as they are in the returned array. Known bug: for for..in loops, the iterate trap is called while it should be the enumerate trap |
for(prop of proxy){...} |
iterate function(target) -> iterator |
|
Object.keys(proxy) |
keys function(target) -> [String] |
|
proxy.apply(thisValue, args) |
apply function(target, thisValue, args) -> any |
|
new proxy(...args) |
construct function(target, args) -> any |
Invariants
Even though proxies provide a lot of power to users, some operations are not trapped in order to keep the language consistent:
- The double and triple equal (
==,===) operator is not trapped.p1 === p2if and only ifp1andp2refer to the same proxy. Object.getPrototypeOf(proxy)unconditionally returnsObject.getPrototypeOf(target)typeof proxyunconditionally returnstypeof targetObject.prototype.toString.call(proxy)unconditionally returnsObject.prototype.toString.call(target)
Examples
Very simple example
An object with 37 as its default value when the property name is not in the object
var handler = {
get: function(target, name){
return name in target?
target[name] :
37;
}
};
var p = new Proxy({}, handler);
p.a = 1;
p.b = undefined;
console.log(p.a, p.b); // 1, undefined
console.log('c' in p, p.c); // false, 37
No-op forwarding proxy
In this example, we are using a native JavaScript object to which our proxy will forward all operations that are applied to it.
var target = {};
var p = new Proxy(target, {});
p.a = 37; // operation forwarded to the proxy
console.log(target.a); // 37. The operation has been properly forwarded
Validation
With a Proxy, you can easily validate the passed value for an object.
let validator = {
set: function(obj, prop, value) {
if (prop === 'age') {
if (!Number.isInteger(value)) {
throw new TypeError('The age is not an integer');
}
if (value > 200) {
throw new RangeError('The age seems invalid');
}
}
// The default behavior to store the value
obj[prop] = value;
}
};
let person = new Proxy({}, validator);
person.age = 100;
console.log(person.age); // 100
person.age = 'young'; // Throws an exception
person.age = 300; // Throws an exception
Manipulating DOM nodes
Sometimes you want to toggle the attribute or class name of two different elements. Here's how:
let view = new Proxy({
selected: null
},
{
set: function(obj, prop, newval) {
let oldval = obj[prop];
if (prop === 'selected') {
if (oldval) {
oldval.setAttribute('aria-selected', 'false');
}
if (newval) {
newval.setAttribute('aria-selected', 'true');
}
}
// The default behavior to store the value
obj[prop] = newval;
}
});
let i1 = view.selected = document.getElementById('item-1');
console.log(i1.getAttribute('aria-selected')); // 'true'
let i2 = view.selected = document.getElementById('item-2');
console.log(i1.getAttribute('aria-selected')); // 'false'
console.log(i2.getAttribute('aria-selected')); // 'true'
Value correction and an extra property
The products proxy object evaluates the passed value and convert it to an array if needed. The object also supports an extra property called latestBrowser both as a getter and a setter.
let products = new Proxy({
browsers: ['Internet Explorer', 'Netscape']
},
{
get: function(obj, prop) {
// An extra property
if (prop === 'latestBrowser') {
return obj.browsers[obj.browsers.length - 1];
}
// The default behavior to return the value
return obj[prop];
},
set: function(obj, prop, value) {
// An extra property
if (prop === 'latestBrowser') {
obj.browsers.push(value);
return;
}
// Convert the value if it is not an array
if (typeof value === 'string') {
value = [value];
}
// The default behavior to store the value
obj[prop] = value;
}
});
console.log(products.browsers); // ['Internet Explorer', 'Netscape']
products.browsers = 'Firefox'; // pass a string (by mistake)
console.log(products.browsers); // ['Firefox'] <- no problem, the value is an array
products.latestBrowser = 'Chrome';
console.log(products.browsers); // ['Firefox', 'Chrome']
console.log(products.latestBrowser); // 'Chrome'
Finding an array item object by its property
This proxy extends an array with some utility features. As you see, you can flexibly "define" properties without using Object.defineProperties. This example can be adapted to find a table row by its cell. In that case, the target will be table.rows.
let products = new Proxy([
{ name: 'Firefox', type: 'browser' },
{ name: 'SeaMonkey', type: 'browser' },
{ name: 'Thunderbird', type: 'mailer' }
],
{
get: function(obj, prop) {
// The default behavior to return the value; prop is usually an integer
if (prop in obj) {
return obj[prop];
}
// Get the number of products; an alias of products.length
if (prop === 'number') {
return obj.length;
}
let result, types = {};
for (let product of obj) {
if (product.name === prop) {
result = product;
}
if (types[product.type]) {
types[product.type].push(product);
} else {
types[product.type] = [product];
}
}
// Get a product by name
if (result) {
return result;
}
// Get products by type
if (prop in types) {
return types[prop];
}
// Get product types
if (prop === 'types') {
return Object.keys(types);
}
return undefined;
}
});
console.log(products[0]); // { name: 'Firefox', type: 'browser' }
console.log(products['Firefox']); // { name: 'Firefox', type: 'browser' }
console.log(products['Chrome']); // undefined
console.log(products.browser); // [{ name: 'Firefox', type: 'browser' }, { name: 'SeaMonkey', type: 'browser' }]
console.log(products.types); // ['browser', 'mailer']
console.log(products.number); // 3
A complete traps list example
Now in order to create a complete sample traps list, for didactic purposes, we will try to proxify a non native object that is particularly suited to this type of operation: the docCookies global object created by the "little framework" published on the document.cookie page.
/*
var docCookies = ... get the "docCookies" object here:
https://developer.mozilla.org/en-US/docs/DOM/document.cookie#A_little_framework.3A_a_complete_cookies_reader.2Fwriter_with_full_unicode_support
*/
var docCookies = new Proxy(docCookies, {
"get": function (oTarget, sKey) {
return oTarget[sKey] || oTarget.getItem(sKey) || undefined;
},
"set": function (oTarget, sKey, vValue) {
if (sKey in oTarget) { return false; }
return oTarget.setItem(sKey, vValue);
},
"delete": function (oTarget, sKey) {
if (sKey in oTarget) { return false; }
return oTarget.removeItem(sKey);
},
"enumerate": function (oTarget, sKey) {
return oTarget.keys();
},
"iterate": function (oTarget, sKey) {
return oTarget.keys();
},
"keys": function (oTarget, sKey) {
return oTarget.keys();
},
"has": function (oTarget, sKey) {
return sKey in oTarget || oTarget.hasItem(sKey);
},
"hasOwn": function (oTarget, sKey) {
return oTarget.hasItem(sKey);
},
"defineProperty": function (oTarget, sKey, oDesc) {
if (oDesc && "value" in oDesc) { oTarget.setItem(sKey, oDesc.value); }
return oTarget;
},
"getPropertyNames": function (oTarget) {
return Object.getPropertyNames(oTarget).concat(oTarget.keys());
},
"getOwnPropertyNames": function (oTarget) {
return Object.getOwnPropertyNames(oTarget).concat(oTarget.keys());
},
"getPropertyDescriptor": function (oTarget, sKey) {
var vValue = oTarget[sKey] || oTarget.getItem(sKey)
return vValue ? {
"value": vValue,
"writable": true,
"enumerable": true,
"configurable": false
} : undefined;
},
"getOwnPropertyDescriptor": function (oTarget, sKey) {
var vValue = oTarget.getItem(sKey);
return vValue ? {
"value": vValue,
"writable": true,
"enumerable": true,
"configurable": false
} : undefined;
},
"fix": function (oTarget) {
return "not implemented yet!";
},
});
/* Cookies test */
alert(docCookies.my_cookie1 = "First value");
alert(docCookies.getItem("my_cookie1"));
docCookies.setItem("my_cookie1", "Changed value");
alert(docCookies.my_cookie1);
See also
- "Proxies are awesome" Brendan Eich presentation at JSConf (slides)
- ECMAScript Harmony Proxy proposal page and ECMAScript Harmony proxy semantics page
- Tutorial on proxies
- Old Proxy API page
Object.watchis a non-standard feature but has been suppoted in Gecko for a long time.
Licensing note
Some content (text, examples) in this page has been copied or adapted from the ECMAScript wiki which content is licensed CC 2.0 BY-NC-SA
Mozilla Developer Network