元编程

ProxyReflect 对象允许你拦截和定义基本语言操作的自定义行为(例如属性查找、赋值、枚举、函数调用等)。借助这两个对象,你可以在 JavaScript 的元级别进行编程。

¥The Proxy and Reflect objects allow you to intercept and define custom behavior for fundamental language operations (e.g. property lookup, assignment, enumeration, function invocation, etc.). With the help of these two objects you are able to program at the meta level of JavaScript.

代理

¥Proxies

Proxy 对象允许你拦截某些操作并实现自定义行为。

¥Proxy objects allow you to intercept certain operations and to implement custom behaviors.

例如,获取对象的属性:

¥For example, getting a property on an object:

js
const handler = {
  get(target, name) {
    return name in target ? target[name] : 42;
  },
};

const p = new Proxy({}, handler);
p.a = 1;
console.log(p.a, p.b); // 1, 42

Proxy 对象定义了一个 target(这里是一个空对象)和一个 handler 对象,其中实现了 get 陷阱。在这里,被代理的对象在获取未定义的属性时不会返回 undefined,而是返回数字 42

¥The Proxy object defines a target (an empty object here) and a handler object, in which a get trap is implemented. Here, an object that is proxied will not return undefined when getting undefined properties, but will instead return the number 42.

Proxy 参考页上提供了其他示例。

¥Additional examples are available on the Proxy reference page.

术语

¥Terminology

在讨论代理的功能时使用以下术语。

¥The following terms are used when talking about the functionality of proxies.

handler

包含陷阱的占位符对象。

traps

提供属性访问的方法。(这类似于操作系统中陷阱的概念。)

target

代理虚拟的对象。它通常用作代理的存储后端。针对对象验证有关对象不可扩展性或不可配置属性的不变量(保持不变的语义)。

invariants

实现自定义操作时保持不变的语义称为不变量。如果违反处理程序的不变量,则会抛出 TypeError

处理程序和陷阱

¥Handlers and traps

下表总结了可用于 Proxy 对象的可用陷阱。请参阅 参考页 了解详细说明和示例。

¥The following table summarizes the available traps available to Proxy objects. See the reference pages for detailed explanations and examples.

处理程序/陷阱 拦截 不变量
handler.getPrototypeOf() Object.getPrototypeOf()
Reflect.getPrototypeOf()
**proto**
Object.prototype.isPrototypeOf()
instanceof
  • getPrototypeOf 方法必须返回一个对象或 null

    ¥ getPrototypeOf method must return an object or null.

  • 如果 target 不可扩展, Object.getPrototypeOf(proxy) 方法必须返回与 Object.getPrototypeOf(target) 相同的值。

    ¥If target is not extensible, Object.getPrototypeOf(proxy) method must return the same value as Object.getPrototypeOf(target).

handler.setPrototypeOf() Object.setPrototypeOf()
Reflect.setPrototypeOf()
如果 target 不可扩展,则 prototype 参数必须与 Object.getPrototypeOf(target) 的值相同。
handler.isExtensible() Object.isExtensible()
Reflect.isExtensible()
Object.isExtensible(proxy) 必须返回与 Object.isExtensible(target) 相同的值。
handler.preventExtensions() Object.preventExtensions()
Reflect.preventExtensions()
如果 Object.isExtensible(proxy)false,则 Object.preventExtensions(proxy) 仅返回 true
handler.getOwnPropertyDescriptor() Object.getOwnPropertyDescriptor()
Reflect.getOwnPropertyDescriptor()
  • getOwnPropertyDescriptor 必须返回一个对象或 undefined

    ¥ getOwnPropertyDescriptor must return an object or undefined.

  • 如果某个属性作为 target 的不可配置自有属性存在,则不能将其报告为不存在。

    ¥A property cannot be reported as non-existent if it exists as a non-configurable own property of target.

  • 如果某个属性作为 target 自己的属性存在,并且 target 不可扩展,则不能将其报告为不存在。

    ¥A property cannot be reported as non-existent if it exists as an own property of target and target is not extensible.

  • 如果属性不作为 target 自己的属性存在,则不能将其报告为存在,并且 target 不可扩展。

    ¥A property cannot be reported as existent if it does not exists as an own property of target and target is not extensible.

  • 如果某个属性不作为 target 自己的属性存在,或者作为 target 的可配置自己的属性存在,则不能将其报告为不可配置。

    ¥A property cannot be reported as non-configurable if it does not exist as an own property of target or if it exists as a configurable own property of target.

  • Object.getOwnPropertyDescriptor(target) 的结果可以使用 Object.defineProperty 应用到 target 并且不会抛出异常。

    ¥The result of Object.getOwnPropertyDescriptor(target) can be applied to target using Object.defineProperty and will not throw an exception.

handler.defineProperty() Object.defineProperty()
Reflect.defineProperty()
  • 如果 target 不可扩展,则无法添加属性。

    ¥A property cannot be added if target is not extensible.

  • 如果某个属性不作为 target 的不可配置自有属性存在,则不能将其添加为(或修改为)不可配置。

    ¥A property cannot be added as (or modified to be) non-configurable if it does not exist as a non-configurable own property of target.

  • 如果 target 存在相应的可配置属性,则该属性可能不是不可配置的。

    ¥A property may not be non-configurable if a corresponding configurable property of target exists.

  • 如果一个属性有对应的目标对象属性,那么 Object.defineProperty(target, prop, descriptor) 不会抛出异常。

    ¥If a property has a corresponding target object property, then Object.defineProperty(target, prop, descriptor) will not throw an exception.

  • 在严格模式下,从 defineProperty 处理程序返回的 false 值将引发 TypeError 异常。

    ¥In strict mode, a false value returned 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()
  • 如果某个属性作为 target 的不可配置自有属性存在,则不能将其报告为不存在。

    ¥A property cannot be reported as non-existent, if it exists as a non-configurable own property of target.

  • 如果某个属性作为 target 自己的属性存在并且 target 不可扩展,则不能将其报告为不存在。

    ¥A property cannot be reported as non-existent if it exists as an own property of target and target is not extensible.

handler.get()
Property access
proxy[foo]
proxy.bar
Inherited property access
Object.create(proxy)[foo]
Reflect.get()
  • 如果 target 的属性是不可写、不可配置的数据属性,则为属性报告的值必须与相应 target 属性的值相同。

    ¥The value reported for a property must be the same as the value of the corresponding target property if target's property is a non-writable, non-configurable data property.

  • 如果相应的 target 属性是未定义为其 [[Get]] 属性的不可配置访问器属性,则为属性报告的值必须为 undefined

    ¥The value reported for a property must be undefined if the corresponding target property is non-configurable accessor property that has undefined as its [[Get]] attribute.

handler.set()
Property assignment
proxy[foo] = bar
proxy.foo = bar
Inherited property assignment
Object.create(proxy)[foo] = bar
Reflect.set()
  • 如果相应的 target 属性是不可写、不可配置的数据属性,则无法将属性值更改为与相应 target 属性的值不同。

    ¥Cannot change the value of a property to be different from the value of the corresponding target property if the corresponding target property is a non-writable, non-configurable data property.

  • 如果相应的 target 属性是具有 undefined 作为其 [[Set]] 属性的不可配置访问器属性,则无法设置属性的值。

    ¥Cannot set the value of a property if the corresponding target property is a non-configurable accessor property that has undefined as its [[Set]] attribute.

  • 在严格模式下, set 处理程序的 false 返回值将引发 TypeError 异常。

    ¥In strict mode, a false return value from the set handler will throw a TypeError exception.

handler.deleteProperty()
Property deletion
delete proxy[foo]
delete proxy.foo
Reflect.deleteProperty()
如果某个属性作为 target 的不可配置自有属性存在,则无法删除。
handler.ownKeys() Object.getOwnPropertyNames()
Object.getOwnPropertySymbols()
Object.keys()
Reflect.ownKeys()
  • ownKeys 的结果是一个列表。

    ¥The result of ownKeys is a List.

  • 每个结果列表元素的类型是 StringSymbol

    ¥The Type of each result List element is either String or Symbol.

  • 结果 List 必须包含 target 所有不可配置的自身属性的键。

    ¥The result List must contain the keys of all non-configurable own properties of target.

  • 如果 target 对象不可扩展,则结果 List 必须包含 target 自身属性的所有键,并且不包含其他值。

    ¥If the target object is not extensible, then the result List must contain all the keys of the own properties of target and no other values.

handler.apply() proxy(..args)
Function.prototype.apply()Function.prototype.call()
Reflect.apply()

    <code><var>handler</var>.apply</code> 方法没有不变量。
  </td>
</tr> 
<tr>
  <td>
    handler.construct()
  </td>
  <td>
    <code>new proxy(...args)</code
    ><br />Reflect.construct()
  </td> 
  <td>结果必须是  <code>Object</code>。</td>
</tr>

可撤销 Proxy

¥Revocable Proxy

Proxy.revocable() 方法用于创建可撤销的 Proxy 对象。这意味着可以通过功能 revoke 撤销代理并关闭代理。

¥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.

此后,对代理的任何操作都会导致 TypeError

¥Afterwards, any operation on the proxy leads to a TypeError.

js
const revocable = Proxy.revocable(
  {},
  {
    get(target, name) {
      return `[[${name}]]`;
    },
  },
);
const proxy = revocable.proxy;
console.log(proxy.foo); // "[[foo]]"

revocable.revoke();

console.log(proxy.foo); // TypeError: Cannot perform 'get' on a proxy that has been revoked
proxy.foo = 1; // TypeError: Cannot perform 'set' on a proxy that has been revoked
delete proxy.foo; // TypeError: Cannot perform 'deleteProperty' on a proxy that has been revoked
console.log(typeof proxy); // "object", typeof doesn't trigger any trap

反射

¥Reflection

Reflect 是一个内置对象,提供可拦截 JavaScript 操作的方法。方法与 代理处理程序的 相同。

¥Reflect is a built-in object that provides methods for interceptable JavaScript operations. The methods are the same as those of the proxy handler's.

Reflect 不是函数对象。

¥Reflect is not a function object.

Reflect 帮助将默认操作从处理程序转发到 target

¥Reflect helps with forwarding default operations from the handler to the target.

Reflect.has() 为例,你可以得到 in 运算符 作为函数:

¥With Reflect.has() for example, you get the in operator as a function:

js
Reflect.has(Object, "assign"); // true

更好的 apply() 函数

¥A better apply() function

Reflect 之前,你通常使用 Function.prototype.apply() 方法来调用具有给定 this 值和作为数组(或 类似数组的对象)提供的 arguments 的函数。

¥Before Reflect, 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).

js
Function.prototype.apply.call(Math.floor, undefined, [1.75]);

使用 Reflect.apply,这变得不那么冗长并且更容易理解:

¥With Reflect.apply this becomes less verbose and easier to understand:

js
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"

检查属性定义是否成功

¥Checking if property definition has been successful

对于 Object.defineProperty,如果成功则返回一个对象,否则抛出 TypeError,你可以使用 try...catch 块来捕获定义属性时发生的任何错误。因为 Reflect.defineProperty() 返回布尔成功状态,所以你可以在此处使用 if...else 块:

¥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:

js
if (Reflect.defineProperty(target, property, attributes)) {
  // success
} else {
  // failure
}