Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Meta programming

Esta traducción está incompleta. Por favor, ayuda a traducir este artículo del inglés.

Comenzando con ECMAScript 6, JavaScript gana soporte para el Proxy y objetos Reflect permitiendote interceptar y definir comportamiento customizado para operaciones fundamentales del lenguaje (por ejemplo, observación de propiedad, 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 customizados. 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 aquí) y un objeto controlador en el cual una trampa get es implementada. Aquí, un objeto que es interceptado no regresará undefined cuando atrapas propiedades indefinidas, sino que regresará el número 42.

Ejemplos adicionales están disponibles en la página de referencia de Proxy.

Terminología

Los siguientes términos son utilizados cuando se habla sobre la funcionalidad de los proxies.

handler
Objeto Placeholder el cual contiene trampas.
trampas
Los métodos que el acceso a la propiedad provee. Esto es análogo al concepto de trampas en sistemas operativos
objetivo
Objeto el cual el proxy visualiza. Es utilizado de forma seguida el backend de almacenamiento para el proxy. Invariantes (semanticas que se mantienen sin cambiar) sin importar inextensibilidad del objeto o las propiedades no-configurables son verificadas contra el objetivo.
invariantes
Semanticas que se mantienen sin cambiar cuando se implementan operaciones customizadas se llaman invariantes. Si violas las invariantes de un controlador, una TypeError será lanzada.

Controladores y trampas

La siguiente tabla resume las trampas disponibles que son disponibles para objetos  Proxy . Vea  paginas de referencias para explicaciones detalladas y ejemplos.

Controlador / Trampa Intercepciones Invariantes
handler.getPrototypeOf() Object.getPrototypeOf()
Reflect.getPrototypeOf()
__proto__
Object.prototype.isPrototypeOf()
instanceof
  • El método getPrototypeOf regresar un objeto o null..
  • If target is not extensible, Object.getPrototypeOf(proxy) method must return the same value as Object.getPrototypeOf(target).
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()
  • getOwnPropertyDescriptor must return an object or undefined.
  • A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object.
  • A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible.
  • A property cannot be reported as existent, if it does not exists as an own property of the target object and the target object is not extensible.
  • A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object.
  • The result of Object.getOwnPropertyDescriptor(target) can be applied to the target object using Object.defineProperty and will not throw an exception.
handler.defineProperty() Object.defineProperty()
Reflect.defineProperty()
  • A property cannot be added, if the target object is not extensible.
  • A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object.
  • A property may not be non-configurable, if a corresponding configurable property of the target object exists.
  • If a property has a corresponding target object property then Object.defineProperty(target, prop, descriptor) will not throw an exception.
  • In strict mode, a false return value from the defineProperty handler will throw a TypeError exception.
handler.has() Property query: foo in proxy
Inherited property query: foo in Object.create(proxy)
Reflect.has()
  • A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object.
  • A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible.
handler.get() Property access: proxy[foo]and proxy.bar
Inherited property access: Object.create(proxy)[foo]
Reflect.get()
  • The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable data property.
  • The value reported for a property must be undefined if the corresponding target object property is non-configurable accessor property that has undefined as its [[Get]] attribute.
handler.set() Property assignment: proxy[foo] = bar and proxy.foo = bar
Inherited property assignment: Object.create(proxy)[foo] = bar
Reflect.set()
  • Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property.
  • Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has undefined as its [[Set]] attribute.
  • In strict mode, a false return value from the set handler will throw a TypeError exception.
handler.deleteProperty() Property deletion: delete proxy[foo] and delete proxy.foo
Reflect.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()
  • The result of ownKeys is a List.
  • The Type of each result List element is either String or Symbol.
  • The result List must contain the keys of all non-configurable own properties of the target object.
  • If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values.
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

The Proxy.revocable() method is used to create a revocable Proxy object. This means that the proxy can be revoked via the function revoke and switches the proxy off. Afterwards, any operation leads on the proxy leads to a 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
}

Etiquetas y colaboradores del documento

 Colaboradores en esta página: jzatarain
 Última actualización por: jzatarain,