元编程
Proxy
和 Reflect
对象允许你拦截和定义基本语言操作的自定义行为(例如属性查找、赋值、枚举、函数调用等)。借助这两个对象,你可以在 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:
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.
可撤销 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
.
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:
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).
Function.prototype.apply.call(Math.floor, undefined, [1.75]);
使用 Reflect.apply
,这变得不那么冗长并且更容易理解:
¥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"
检查属性定义是否成功
¥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:
if (Reflect.defineProperty(target, property, attributes)) {
// success
} else {
// failure
}