Proxy() 构造函数

Proxy() 构造函数创建 Proxy 对象。

¥The Proxy() constructor creates Proxy objects.

语法

¥Syntax

js
new Proxy(target, handler)

注意:Proxy() 只能与 new 一起构建。尝试在没有 new 的情况下调用它会抛出 TypeError

¥Note: Proxy() can only be constructed with new. Attempting to call it without new throws a TypeError.

参数

¥Parameters

target

Proxy 封装的目标对象。它可以是任何类型的对象,包括原生数组、函数,甚至另一个代理。

handler

一个对象,其属性是定义代理在对其执行操作时的行为的函数。

描述

¥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()

Object.defineProperty 的陷阱。

handler.deleteProperty()

delete 运算符的陷阱。

handler.get()

获取属性值的陷阱。

handler.getOwnPropertyDescriptor()

Object.getOwnPropertyDescriptor 的陷阱。

handler.getPrototypeOf()

Object.getPrototypeOf 的陷阱。

handler.has()

in 运算符的陷阱。

handler.isExtensible()

Object.isExtensible 的陷阱。

handler.ownKeys()

Object.getOwnPropertyNamesObject.getOwnPropertySymbols 的陷阱。

handler.preventExtensions()

Object.preventExtensions 的陷阱。

handler.set()

设置属性值的陷阱。

handler.setPrototypeOf()

Object.setPrototypeOf 的陷阱。

示例

¥Examples

有选择地代理属性访问器

¥Selectively proxy property accessors

在此示例中,目标有两个属性:notProxiedproxied。我们定义一个处理程序,为 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.

js
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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also