Monday, January 4, 2016

Preparing for ECMAScript 6: Proxies

In computing terms, a proxy sits between you and the thing you are 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:

[author_more]

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:

[code]
var target = {
a: 1,
b: 2,
c: 3
};
[/code]

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:

[code]
var handler = {

get: function(target, name) {
return (
name in target ? target[name] : 42
);
}

};
[/code]

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:

[code]
var 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
[/code]

Let's expand the proxy handler further so it only permits single-character properties from a to z to be set:

[code]
var 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;
}
}

};

var proxy = new Proxy(target, handler);

proxy.a = 10;
proxy.b = 20;
proxy.ABC = 30;
// Exception: ReferenceError: ABC cannot be set

[/code]

Continue reading %Preparing for ECMAScript 6: Proxies%


by Craig Buckler via SitePoint

No comments:

Post a Comment