Skip to content

Commit a0b3bd9

Browse files
committed
первая часть
1 parent 046adfe commit a0b3bd9

File tree

1 file changed

+35
-35
lines changed

1 file changed

+35
-35
lines changed

1-js/99-js-misc/01-proxy/article.md

Lines changed: 35 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ let proxy = new Proxy(target, handler)
1414
- `target` -- это объект, который обёртывается, может быть чем угодно, включая функции.
1515
- `handler` -- объект с "ловушками" ("traps"): методами, которые перехватывают разные операции, например `get` при чтении свойства, `set` при записи свойства и так далее.
1616

17-
Если в свойстве `handler` объекта `proxy` имеется соответствующая "ловушка", то она срабатывает, и прокси имеет возможность как-то среагировать, иначе же действовать будет уже оригинальный объект из `target`.
17+
Если в `handler` объекта `proxy` имеется соответствующая "ловушка", то она срабатывает, и прокси имеет возможность как-то среагировать, иначе же действовать будет уже оригинальный объект из `target`.
1818

1919
В качестве примера давайте для начала создадим прокси без всяких ловушек:
2020

@@ -30,7 +30,7 @@ alert(proxy.test); // 5, мы также можем прочитать его и
3030
for(let key in proxy) alert(key); // test, итерация работает (3)
3131
```
3232

33-
Так как нет ловушек, то все операции на `proxy` в итоге применяются к `target`.
33+
Так как нет ловушек, то все операции на `proxy` в итоге применяются к оригинальному объекту `target`.
3434

3535
1. Запись свойства `proxy.test=` устанавливает значение на `target`.
3636
2. Чтение свойства `proxy.test` возвращает значение из `target`.
@@ -40,50 +40,50 @@ for(let key in proxy) alert(key); // test, итерация работает (3)
4040

4141
![](proxy.png)
4242

43-
Прокси -- это особенный объект, у него нет собственных свойств. С пустым handler он просто перенапрвляет все операции на `target`.
43+
Прокси -- это особенный объект, у него нет собственных свойств. С пустым `handler` он просто перенаправляет все операции на `target`.
4444

45-
Если мы хотим какой-то придать ему какую-то магическую силу, то следует добавить ловушки.
45+
Если мы хотим придать ему какую-то магическую силу, то следует добавить ловушки.
4646

47-
Вот список внутренних методов объектов из [спецификации Proxy](https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots). Прокси может перехватывать вызов любого из них, нужно только добавить соответствующий обработчик.
47+
Вот список внутренних методов объектов из [спецификации Proxy](https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots). Прокси может перехватывать вызов любого из них, нужно только добавить соответствующий обработчик в `handler`.
4848

4949
В таблице ниже:
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-
- **Handler Method** is a method name that we should add to proxy `handler` to trap the operation and perform custom actions.
50+
- **Внутренний метод** -- название операции над объектом, определённое в спецификации. Например, `[[Get]]` -- это имя внутреннего метода для чтения свойства объекта. В спецификации описывается, как это должно быть реализовано, до мельчайших низкоуровневых подробностей.
51+
- **Ловушка** -- это имя метода, который мы можем добавить в параметр `handler` при создании прокси. Этот метод будет действовать как ловушка, перехватывая операции над объектом и позволяя совершать над ним какие-то дополнительные действия.
5252

5353

54-
| Internal Method | Handler Method | Traps... |
54+
| Внутренний метод | Ловушка | Срабатывает при... |
5555
|-----------------|----------------|-------------|
56-
| `[[Get]]` | `get` | reading a property |
57-
| `[[Set]]` | `set` | writing to a property |
58-
| `[[HasProperty]]` | `has` | `in` operator |
59-
| `[[Delete]]` | `deleteProperty` | `delete` operator |
60-
| `[[Call]]` | `apply` | function call |
61-
| `[[Construct]]` | `construct` | `new` operator |
62-
| `[[GetPrototypeOf]]` | `getPrototypeOf` | [Object.getPrototypeOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf) |
63-
| `[[SetPrototypeOf]]` | `setPrototypeOf` | [Object.setPrototypeOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf) |
64-
| `[[IsExtensible]]` | `isExtensible` | [Object.isExtensible](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible) |
65-
| `[[PreventExtensions]]` | `preventExtensions` | [Object.preventExtensions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions) |
66-
| `[[GetOwnProperty]]` | `getOwnPropertyDescriptor` | [Object.getOwnPropertyDescriptor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor) |
67-
| `[[DefineOwnProperty]]` | `defineProperty` | [Object.defineProperty](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty), [Object.defineProperties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties) |
68-
| `[[OwnPropertyKeys]]` | `ownKeys` | [Object.keys](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), [Object.getOwnPropertyNames](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames), [Object.getOwnPropertySymbols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols), iteration keys |
56+
| `[[Get]]` | `get` | чтении свойства |
57+
| `[[Set]]` | `set` | записи свойства |
58+
| `[[HasProperty]]` | `has` | использовании в операторе `in` |
59+
| `[[Delete]]` | `deleteProperty` | при использовании оператора `delete` |
60+
| `[[Call]]` | `apply` | вызове функции |
61+
| `[[Construct]]` | `construct` | использовании оператора `new` |
62+
| `[[GetPrototypeOf]]` | `getPrototypeOf` | [Object.getPrototypeOf](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf) |
63+
| `[[SetPrototypeOf]]` | `setPrototypeOf` | [Object.setPrototypeOf](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf) |
64+
| `[[IsExtensible]]` | `isExtensible` | [Object.isExtensible](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible) |
65+
| `[[PreventExtensions]]` | `preventExtensions` | [Object.preventExtensions](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions) |
66+
| `[[GetOwnProperty]]` | `getOwnPropertyDescriptor` | [Object.getOwnPropertyDescriptor](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor) |
67+
| `[[DefineOwnProperty]]` | `defineProperty` | [Object.defineProperty](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty), [Object.defineProperties](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties) |
68+
| `[[OwnPropertyKeys]]` | `ownKeys` | [Object.keys](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), [Object.getOwnPropertyNames](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames), [Object.getOwnPropertySymbols](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols), итерация по ключам |
6969

70-
```warn header="Invariants"
71-
JavaScript enforces some invariants -- conditions that must be fulfilled by internal methods and traps.
70+
```warn header="Инварианты"
71+
JavaScript предполагает, что при реализации внутренних методов и ловушек в коде будут выполнены определённые условия -- инварианты.
7272
73-
Most of them are for return values:
74-
- `[[Set]]` must return `true` if the value was written successfully, otherwise `false`.
75-
- `[[Delete]]` must return `true` if the value was deleted successfully, otherwise `false`.
76-
- ...and so on, we'll see more in examples below.
73+
Большинство из них касаются возвращаемых значений:
74+
- `[[Set]]` должен возвращать `true`, если значение было успешно записано, иначе `false`.
75+
- `[[Delete]]` должен возвращать `true`, если значение было успешно удалено, иначе `false`.
76+
- ...и так далее, мы ещё столкнёмся с этим в примерах ниже.
7777
78-
There are some other invariants, like:
79-
- `[[GetPrototypeOf]]`, applied to the proxy object must return the same value as `[[GetPrototypeOf]]` applied to the proxy object's target object.
78+
Но есть и другие условия:
79+
- `[[GetPrototypeOf]]`, применённый к прокси, должен возвращать то же значение, что и метод `[[GetPrototypeOf]]`, применённый к оригинальному объекту.
8080
81-
In other words, reading prototype of a `proxy` must always return the prototype of the target object. The `getPrototypeOf` trap may intercept this operation, but it must follow this rule, not do something crazy.
81+
Другими словами, чтение прототипа объекта `proxy` всегда должно возвращать прототип оригинального объекта. Ловушка `getPrototypeOf` может перехватывать эту операцию, но в любом случае должна выполнять указанное условие, а не делать что-то сумасшедшее.
8282
83-
Invariants ensure correct and consistent behavior of language features. The full invariants list is in [the specification](https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots), you probably won't violate them, if not doing something weird.
83+
Инварианты гарантируют корректное и последовательное поведение конструкций и методов языка. Полный список инвариантов можно найти в [спецификации](https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots), хотя скорее всего вы не нарушите эти условия, если только не соберётесь делать что-то совсем уж странное.
8484
```
8585

86-
Let's see how that works on practical examples.
86+
Теперь давайте посмотрим, как это всё работает на реальных примерах.
8787

8888
## Default value with "get" trap
8989

@@ -840,7 +840,7 @@ Using `WeakMap` instead of `Map` here, because it should not block garbage colle
840840
## References
841841
842842
- Specification: [Proxy](https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots).
843-
- MDN: [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy).
843+
- MDN: [Proxy](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Proxy).
844844
845845
## Summary
846846
@@ -861,13 +861,13 @@ let proxy = new Proxy(target, {
861861
We can trap:
862862
- Reading (`get`), writing (`set`), deleting (`deleteProperty`) a property (even a non-existing one).
863863
- Calling functions with `new` (`construct` trap) and without `new` (`apply` trap)
864-
- Many other operations (the full list is at the beginning of the article and in the [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy)).
864+
- Many other operations (the full list is at the beginning of the article and in the [docs](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Proxy)).
865865
866866
That allows us to create "virtual" properties and methods, implement default values, observable objects, function decorators and so much more.
867867
868868
We can also wrap an object multiple times in different proxies, decorating it with various aspects of functionality.
869869
870-
The [Reflect](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect) API is designed to complement [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy). For any `Proxy` trap, there's a `Reflect` call with same arguments. We should use those to forward calls to target objects.
870+
The [Reflect](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Reflect) API is designed to complement [Proxy](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Proxy). For any `Proxy` trap, there's a `Reflect` call with same arguments. We should use those to forward calls to target objects.
871871
872872
Proxies have some limitations:
873873

0 commit comments

Comments
 (0)