|
1 | 1 |
|
2 | | -# Proxy and Reflect |
| 2 | +# Proxy и Reflect |
3 | 3 |
|
4 | | -A *proxy* wraps another object and intercepts operations, like reading/writing properties and others, optionally handling them on its own, or transparently allowing the object to handle them. |
| 4 | +Объект *proxy* служит обёрткой для другого объекта, а также перехватывает и (опционально) обрабатывает разные действия, например чтение/запись свойств и другие, производимые с оригинальным объектом. |
5 | 5 |
|
6 | | -Proxies are used in many libraries and some browser frameworks. We'll see many practical applications in this chapter. |
| 6 | +Прокси используются во многих библиотеках и некоторых браузерных фреймворках. В этой главе мы увидим много случаев применения прокси в решении реальных задач. |
7 | 7 |
|
8 | | -The syntax: |
| 8 | +Синтаксис: |
9 | 9 |
|
10 | 10 | ```js |
11 | 11 | let proxy = new Proxy(target, handler) |
12 | 12 | ``` |
13 | 13 |
|
14 | | -- `target` -- is an object to wrap, can be anything, including functions. |
15 | | -- `handler` -- an object with "traps": methods that intercept operations., e.g. `get` for reading a property, `set` for writing a property, etc. |
| 14 | +- `target` -- это объект, который обёртывается, может быть чем угодно, включая функции. |
| 15 | +- `handler` -- объект с "ловушками" ("traps"): методами, которые перехватывают разные операции, например `get` при чтении свойства, `set` при записи свойства и так далее. |
16 | 16 |
|
17 | | -For operations on `proxy`, if there's a corresponding trap in `handler`, then it runs, and the proxy has a chance to handle it, otherwise the operation is performed on `target`. |
| 17 | +Если в свойстве `handler` объекта `proxy` имеется соответствующая "ловушка", то она срабатывает, и прокси имеет возможность как-то среагировать, иначе же действовать будет уже оригинальный объект из `target`. |
18 | 18 |
|
19 | | -As a starting example, let's create a proxy without any traps: |
| 19 | +В качестве примера давайте для начала создадим прокси без всяких ловушек: |
20 | 20 |
|
21 | 21 | ```js run |
22 | 22 | let target = {}; |
23 | | -let proxy = new Proxy(target, {}); // empty handler |
| 23 | +let proxy = new Proxy(target, {}); // пустой handler |
24 | 24 |
|
25 | | -proxy.test = 5; // writing to proxy (1) |
26 | | -alert(target.test); // 5, the property appeared in target! |
| 25 | +proxy.test = 5; // записываем в прокси (1) |
| 26 | +alert(target.test); // 5, свойство появилось в target! |
27 | 27 |
|
28 | | -alert(proxy.test); // 5, we can read it from proxy too (2) |
| 28 | +alert(proxy.test); // 5, мы также можем прочитать его из прокси (2) |
29 | 29 |
|
30 | | -for(let key in proxy) alert(key); // test, iteration works (3) |
| 30 | +for(let key in proxy) alert(key); // test, итерация работает (3) |
31 | 31 | ``` |
32 | 32 |
|
33 | | -As there are no traps, all operations on `proxy` are forwarded to `target`. |
| 33 | +Так как нет ловушек, то все операции на `proxy` в итоге применяются к `target`. |
34 | 34 |
|
35 | | -1. A writing operation `proxy.test=` sets the value on `target`. |
36 | | -2. A reading operation `proxy.test` returns the value from `target`. |
37 | | -3. Iteration over `proxy` returns values from `target`. |
| 35 | +1. Запись свойства `proxy.test=` устанавливает значение на `target`. |
| 36 | +2. Чтение свойства `proxy.test` возвращает значение из `target`. |
| 37 | +3. Итерация по `proxy` возвращает значения из `target`. |
38 | 38 |
|
39 | | -As we can see, without any traps, `proxy` is a transparent wrapper around `target`. |
| 39 | +Как мы видим, без ловушек `proxy` является прозрачной обёрткой над `target`. |
40 | 40 |
|
41 | 41 |  |
42 | 42 |
|
43 | | -The proxy is a special "exotic object". It doesn't have "own" properties. With an empty handler it transparently forwards operations to `target`. |
| 43 | +Прокси -- это особенный объект, у него нет собственных свойств. С пустым handler он просто перенапрвляет все операции на `target`. |
44 | 44 |
|
45 | | -If we want any magic, we should add traps. |
| 45 | +Если мы хотим какой-то придать ему какую-то магическую силу, то следует добавить ловушки. |
46 | 46 |
|
47 | | -There's a list of internal object operations in the [Proxy specification](https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots). A proxy can intercept any of these, we just need to add a handler method. |
| 47 | +Вот список внутренних методов объектов из [спецификации Proxy](https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots). Прокси может перехватывать вызов любого из них, нужно только добавить соответствующий обработчик. |
48 | 48 |
|
49 | | -In the table below: |
| 49 | +В таблице ниже: |
50 | 50 | - **Internal Method** is the specification-specific name for the operation. For example, `[[Get]]` is the name of the internal, specification-only method of reading a property. The specification describes how this is done at the very lowest level. |
51 | 51 | - **Handler Method** is a method name that we should add to proxy `handler` to trap the operation and perform custom actions. |
52 | 52 |
|
|
0 commit comments