This translation is incomplete. Please help translate this article from English
Comenzando con ECMAScript 6, JavaScript gana soporte para el Proxy y objetos Reflect permitiendote interceptar y definir comportamiento personalizado para operaciones fundamentales del lenguaje (por ejemplo, observación de propiedades, asignación, enumeración, invocación de funciones, etc). Con la ayuda de estos dos objetos, eres capaz de programar en el nivel meta de javascript.
Proxies
Introducido en ECMAScript 6, objetos Proxy te permiten interceptar ciertas operaciones e implementar comportamientos personalizados.
Por ejemplo, obteniendo una propiedad de un objeto:
var handler = {
get: function(target, name){
return name in target ? target[name] : 42;
}
};
var p = new Proxy({}, handler);
p.a = 1;
console.log(p.a, p.b); // 1, 42
El objeto Proxy define un objetivo (un objeto vacío aquí) y un objeto controlador en el que se implementa una trampa get. Aquí, un objeto que es interceptado no devolverá undefined cuando se atrapen propiedades indefinidas, sino que en su lugar devolverá el número 42.
Hay disponibles ejemplos adicionales en la página de referencia de Proxy.
Terminología
Los siguientes términos se usan cuando se habla sobre la funcionalidad de los proxies.
- handler
- Objeto Placeholder que contiene trampas.
- trampas
- Los métodos que proporcionan acceso a la propiedad. (Esto es análogo al concepto de trampas en sistemas operativos)
- objetivo
- Objeto que virtualiza el proxy. Se utiliza con frecuencia como almacén de reserva para el proxy. Los Invariantes (semánticas que permanecen sin cambios) relacionados con la no extesibilidad del objeto o las propiedades no configurables se verifican contra el objetivo.
- invariantes
- Se llama invariantes a las semánticas que se mantienen sin cambiar cuando se implementan operaciones personalizadas. Si violas las invariantes de un controlador, se lanzará una
TypeError.
Controladores y trampas
La siguiente tabla resume las trampas disponibles que están disponibles para objetos Proxy . Vea las páginas de referencia para explicaciones detalladas y ejemplos.
| Controlador / Trampa | Intercepciones | Invariantes |
|---|---|---|
handler.getPrototypeOf() |
Object.getPrototypeOf()Reflect.getPrototypeOf()__proto__Object.prototype.isPrototypeOf()instanceof |
|
handler.setPrototypeOf() |
Object.setPrototypeOf()Reflect.setPrototypeOf() |
If target is not extensible, the prototype parameter must be the same value as Object.getPrototypeOf(target). |
handler.isExtensible() |
Object.isExtensible()Reflect.isExtensible() |
Object.isExtensible(proxy) must return the same value as Object.isExtensible(target). |
handler.preventExtensions() |
Object.preventExtensions()Reflect.preventExtensions() |
Object.preventExtensions(proxy) only returns true if Object.isExtensible(proxy) is false. |
handler.getOwnPropertyDescriptor() |
Object.getOwnPropertyDescriptor()Reflect.getOwnPropertyDescriptor() |
|
handler.defineProperty() |
Object.defineProperty()Reflect.defineProperty() |
|
handler.has() |
Property query: foo in proxyInherited property query: foo in Object.create(proxy)Reflect.has() |
|
handler.get() |
Property access: proxy[foo]and proxy.barInherited property access: Object.create(proxy)[foo]Reflect.get() |
|
handler.set() |
Property assignment: proxy[foo] = bar and proxy.foo = barInherited property assignment: Object.create(proxy)[foo] = barReflect.set() |
|
handler.deleteProperty() |
Property deletion: delete proxy[foo] and delete proxy.fooReflect.deleteProperty() |
A property cannot be deleted, if it exists as a non-configurable own property of the target object. |
handler.enumerate() |
Property enumeration / for...in: for (var name in proxy) {...}Reflect.enumerate() |
The enumerate method must return an object. |
handler.ownKeys() |
Object.getOwnPropertyNames()Object.getOwnPropertySymbols()Object.keys()Reflect.ownKeys() |
|
handler.apply() |
proxy(..args)Function.prototype.apply() and Function.prototype.call()Reflect.apply() |
There are no invariants for the handler.apply method. |
handler.construct() |
new proxy(...args)Reflect.construct() |
The result must be an Object. |
Proxy revocable
El método Proxy.revocable () se usa para crear un objeto Proxy revocable. Esto significa que el proxy se puede revocar mediante la función revocar y apaga el proxy. Luego, cualquier operación conduce en el proxy conduce a un TypeError.
var revocable = Proxy.revocable({}, {
get: function(target, name) {
return "[[" + name + "]]";
}
});
var proxy = revocable.proxy;
console.log(proxy.foo); // "[[foo]]"
revocable.revoke();
console.log(proxy.foo); // TypeError is thrown
proxy.foo = 1 // TypeError again
delete proxy.foo; // still TypeError
typeof proxy // "object", typeof doesn't trigger any trap
Reflexión
Reflect is a built-in object that provides methods for interceptable JavaScript operations. The methods are the same as those of the proxy handlers. Reflect is not a function object.
Reflect helps with forwarding default operations from the handler to the target.
With Reflect.has() for example, you get the in operator as a function:
Reflect.has(Object, "assign"); // true
Una mejor función apply
In ES5, you typically use the Function.prototype.apply() method to call a function with a given this value and arguments provided as an array (or an array-like object).
Function.prototype.apply.call(Math.floor, undefined, [1.75]);
With Reflect.apply this becomes less verbose and easier to understand:
Reflect.apply(Math.floor, undefined, [1.75]);
// 1;
Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]);
// "hello"
Reflect.apply(RegExp.prototype.exec, /ab/, ["confabulation"]).index;
// 4
Reflect.apply("".charAt, "ponies", [3]);
// "i"
Checando si la definición de propiedad ha sido exitosa
With Object.defineProperty, which returns an object if successful, or throws a TypeError otherwise, you would use a try...catch block to catch any error that occurred while defining a property. Because Reflect.defineProperty returns a Boolean success status, you can just use an if...else block here:
if (Reflect.defineProperty(target, property, attributes)) {
// success
} else {
// failure
}

