Proxy() 构造函数
语法
参数
描述
¥Description
使用 Proxy() 构造函数创建一个新的 Proxy 对象。该构造函数采用两个强制参数:
¥Use the Proxy() constructor to create a new Proxy object.
This constructor takes two mandatory arguments:
target是你要为其创建代理的对象handler是定义代理的自定义行为的对象。
空处理程序将创建一个代理,其行为几乎在所有方面都与目标完全相同。通过在 handler 对象上定义任意一组函数,你可以自定义代理行为的特定方面。例如,通过定义 get(),你可以提供目标 属性访问器 的自定义版本。
¥An empty handler will create a proxy that behaves, in almost all respects, exactly like
the target. By defining any of a set group of functions on the handler
object, you can customize specific aspects of the proxy's behavior. For example, by
defining get() you can provide a customized version of the target's
property accessor.
处理函数
¥Handler functions
本节列出了你可以定义的所有处理程序函数。处理程序函数有时称为陷阱,因为它们捕获对底层目标对象的调用。
¥This section lists all the handler functions you can define. Handler functions are sometimes called traps, because they trap calls to the underlying target object.
handler.apply()-
函数调用的陷阱。
handler.construct()-
new运算符的陷阱。 handler.defineProperty()handler.deleteProperty()-
delete运算符的陷阱。 handler.get()-
获取属性值的陷阱。
handler.getOwnPropertyDescriptor()handler.getPrototypeOf()handler.has()-
in运算符的陷阱。 handler.isExtensible()-
Object.isExtensible的陷阱。 handler.ownKeys()-
Object.getOwnPropertyNames和Object.getOwnPropertySymbols的陷阱。 handler.preventExtensions()handler.set()-
设置属性值的陷阱。
handler.setPrototypeOf()
示例
有选择地代理属性访问器
¥Selectively proxy property accessors
在此示例中,目标有两个属性:notProxied 和 proxied。我们定义一个处理程序,为 proxied 返回不同的值,并允许任何其他访问到达目标。
¥In this example the target has two properties, notProxied and
proxied. We define a handler that returns a different value for
proxied, and lets any other accesses through to the target.
const target = {
notProxied: "original value",
proxied: "original value",
};
const handler = {
get(target, prop, receiver) {
if (prop === "proxied") {
return "replaced value";
}
return Reflect.get(...arguments);
},
};
const proxy = new Proxy(target, handler);
console.log(proxy.notProxied); // "original value"
console.log(proxy.proxied); // "replaced value"
规范
| Specification |
|---|
| ECMAScript Language Specification # sec-proxy-constructor |
浏览器兼容性
BCD tables only load in the browser