You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/99-js-misc/01-proxy/article.md
+35-35Lines changed: 35 additions & 35 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -14,7 +14,7 @@ let proxy = new Proxy(target, handler)
14
14
-`target` -- это объект, который обёртывается, может быть чем угодно, включая функции.
15
15
-`handler` -- объект с "ловушками" ("traps"): методами, которые перехватывают разные операции, например `get` при чтении свойства, `set` при записи свойства и так далее.
16
16
17
-
Если в свойстве `handler` объекта `proxy` имеется соответствующая "ловушка", то она срабатывает, и прокси имеет возможность как-то среагировать, иначе же действовать будет уже оригинальный объект из`target`.
17
+
Если в `handler` объекта `proxy` имеется соответствующая "ловушка", то она срабатывает, и прокси имеет возможность как-то среагировать, иначе же действовать будет уже оригинальный объект из `target`.
18
18
19
19
В качестве примера давайте для начала создадим прокси без всяких ловушек:
20
20
@@ -30,7 +30,7 @@ alert(proxy.test); // 5, мы также можем прочитать его и
30
30
for(let key in proxy) alert(key); // test, итерация работает (3)
31
31
```
32
32
33
-
Так как нет ловушек, то все операции на `proxy` в итоге применяются к `target`.
33
+
Так как нет ловушек, то все операции на `proxy` в итоге применяются к оригинальному объекту `target`.
34
34
35
35
1. Запись свойства `proxy.test=` устанавливает значение на `target`.
36
36
2. Чтение свойства `proxy.test` возвращает значение из `target`.
@@ -40,50 +40,50 @@ for(let key in proxy) alert(key); // test, итерация работает (3)
40
40
41
41

42
42
43
-
Прокси -- это особенный объект, у него нет собственных свойств. С пустым handler он просто перенапрвляет все операции на `target`.
43
+
Прокси -- это особенный объект, у него нет собственных свойств. С пустым `handler` он просто перенаправляет все операции на `target`.
44
44
45
-
Если мы хотим какой-то придать ему какую-то магическую силу, то следует добавить ловушки.
45
+
Если мы хотим придать ему какую-то магическую силу, то следует добавить ловушки.
46
46
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`.
48
48
49
49
В таблице ниже:
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`при создании прокси. Этот метод будет действовать как ловушка, перехватывая операции над объектом и позволяя совершать над ним какие-то дополнительные действия.
|`[[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), итерация по ключам|
69
69
70
-
```warn header="Invariants"
71
-
JavaScript enforces some invariants -- conditions that must be fulfilled by internal methods and traps.
70
+
```warn header="Инварианты"
71
+
JavaScript предполагает, что при реализации внутренних методов и ловушек в коде будут выполнены определённые условия -- инварианты.
72
72
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
+
- ...и так далее, мы ещё столкнёмся с этим в примерах ниже.
77
77
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]]`, применённый к оригинальному объекту.
80
80
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` может перехватывать эту операцию, но в любом случае должна выполнять указанное условие, а не делать что-то сумасшедшее.
82
82
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), хотя скорее всего вы не нарушите эти условия, если только не соберётесь делать что-то совсем уж странное.
84
84
```
85
85
86
-
Let's see how that works on practical examples.
86
+
Теперь давайте посмотрим, как это всё работает на реальных примерах.
87
87
88
88
## Default value with "get" trap
89
89
@@ -840,7 +840,7 @@ Using `WeakMap` instead of `Map` here, because it should not block garbage colle
@@ -861,13 +861,13 @@ let proxy = new Proxy(target, {
861
861
We can trap:
862
862
- Reading (`get`), writing (`set`), deleting (`deleteProperty`) a property (even a non-existing one).
863
863
- 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)).
865
865
866
866
That allows us to create "virtual" properties and methods, implement default values, observable objects, function decorators and so much more.
867
867
868
868
We can also wrap an object multiple times in different proxies, decorating it with various aspects of functionality.
869
869
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.
0 commit comments