The Proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object. Proxy对象让我们可以为另一个对象创建一个代理。这个代理可以拦截目标对象的调用、重新定义其基本操作。

Description

描述

A Proxy is created with two parameters: 一个代理对象创建时需要两个参数:

  • target: the original object which you want to proxy 目标对象:被代理的原始对象
  • handler: an object that defines which operations will be intercepted and how to redefine intercepted operations. 处理器:一个定义拦截操作、并重写调用操作的对象。 For example, this code defines a simple target with just two properties, and an even simpler handler with no properties: 例如,下面的代码片段就定义了一个只有两个属性的简单目标对象,和一个嘛也没有的处理器: ```JavaScript const target = { message1: “hello”, message2: “everyone” };

const handler1 = {};

const proxy1 = new Proxy(target, handler1);


Because the handler is empty, this proxy behaves just like the original target:
因为处理器是空的,代理行为可视为透明:

```JavaScript
console.log(proxy1.message1); // hello
console.log(proxy1.message2); // everyone

To customise the proxy, we define functions on the handler object: 为了实现自定义功能,我们在处理器上定义些函数:

const target = {
  message1: "hello",
  message2: "everyone"
};

const handler2 = {
  get: function(target, prop, receiver) {
    return "world";
  }
};

const proxy2 = new Proxy(target, handler2);

Here we’ve provided an implementation of the get() handler, which intercepts attempts to access properties in the target. 上面代码中,我们提供了get方法的处理函数,通过它来拦截目标对象上属性的访问请求。 Handler functions are sometimes called traps, presumably because they trap calls to the target object. The very simple trap in handler2 above redefines all property accessors: 处理器函数有时被称作捕捉器(Trap),许是因为它们可以捕捉到对目标对象的调用请求。上面代码中定义了一个非常简单的、对所有属性访问请求的捕捉行为:

console.log(proxy2.message1); // world
console.log(proxy2.message2); // world

With the help of the Reflect class we can give some accessors the original behavior and redefine others: 通过使用Reflect类,我们可以为部分访问行为提供原始实现,而另一部分来自定义:

const target = {
  message1: "hello",
  message2: "everyone"
};

const handler3 = {
  get: function (target, prop, receiver) {
    if (prop === "message2") {
      return "world";
    }
    return Reflect.get(...arguments);
  },
};

const proxy3 = new Proxy(target, handler3);

console.log(proxy3.message1); // hello
console.log(proxy3.message2); // world