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
+58-59Lines changed: 58 additions & 59 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,66 +1,65 @@
1
-
# Proxy and Reflect
1
+
# Proxy e Reflect
2
2
3
-
A `Proxy`object 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.
3
+
Un oggetto `Proxy`racchiude un altro oggetto e ne intercetta le operazioni, come quelle di lettura/scrittura e molte altre, può eventualmente gestirle a modo suo, oppure, in maniera del tutto trasparente, lasciare che sia l'oggetto ad occuoparsene.
4
4
5
-
Proxies are used in many libraries and some browser frameworks. We'll see many practical applications in this article.
5
+
I proxy vengono utilizzati da molte librerie ed alcuni framework per browsers. Ne vedremo molte applicazioni pratiche in questo articolo.
6
6
7
7
## Proxy
8
8
9
-
The syntax:
9
+
La sintassi:
10
10
11
11
```js
12
12
let proxy =newProxy(target, handler)
13
13
```
14
14
15
-
-`target` -- is an object to wrap, can be anything, including functions.
16
-
-`handler` -- proxy configuration: an object with "traps", methods that intercept operations. - e.g. `get`trap for reading a property of `target`, `set`trap for writing a property into `target`, and so on.
15
+
-`target` -- è l'oggetto da racchiudere, può essere qualsiasi cosa, anche funzioni.
16
+
-`handler` -- configurazione del proxy: un oggetto con "trappole", metodi che intercettano operazioni. Ad esempio una "trappola" `get`per la lettura di una proprietà di `target`, `set`per la scrittura di una prorietà di `target`, e così via.
17
17
18
-
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`.
19
-
20
-
As a starting example, let's create a proxy without any traps:
18
+
Per le operazioni sul `proxy`, se c'è un "tappola" corrispondente in `handler`, allora questa verrà eseguita, e il proxy potrà gestirla, altrimenti l'operazione verrà eseguita su `target`.
19
+
Come primo esempio, creiamo un proxy senza "trappole":
21
20
22
21
```js run
23
22
let target = {};
24
-
let proxy =newProxy(target, {}); //empty handler
23
+
let proxy =newProxy(target, {}); // handler vuoto
25
24
26
-
proxy.test=5; //writing to proxy (1)
27
-
alert(target.test); // 5, the property appeared in target!
25
+
proxy.test=5; //scrittura su proxy (1)
26
+
alert(target.test); // 5, la proprietà si trova su target!
28
27
29
-
alert(proxy.test); // 5, we can read it from proxy too (2)
28
+
alert(proxy.test); // 5, possiamo leggerla anche dal proxy (2)
30
29
31
-
for(let key in proxy) alert(key); // test, iteration works (3)
30
+
for(let key in proxy) alert(key); // test, l'iterazione funziona (3)
32
31
```
33
32
34
-
As there are no traps, all operations on `proxy`are forwarded to`target`.
33
+
Poiché non ci sono "trappole", tutte le operazioni su `proxy`vengono inoltrate a`target`.
35
34
36
-
1.A writing operation`proxy.test=`sets the value on`target`.
37
-
2.A reading operation`proxy.test`returns the value from`target`.
As we can see, without any traps, `proxy`is a transparent wrapper around`target`.
39
+
Come possiamo vedere, senza "trappole", `proxy`è solamente un contenitore per`target`.
41
40
42
41

43
42
44
-
`Proxy`is a special "exotic object". It doesn't have own properties. With an empty `handler`it transparently forwards operations to`target`.
43
+
`Proxy`è uno speciale "oggetto esotico". Non possiede proprietà proprie. Con un `handler`vuoto, le operazioni verranno automaticamente inoltrate a`target`.
45
44
46
-
To activate more capabilities, let's add traps.
45
+
Per attivare più funzionalità, aggiungiamo qualche "trappola".
47
46
48
-
What can we intercept with them?
47
+
Cosa possiamo intercettare?
49
48
50
-
For most operations on objects, there's a so-called "internal method" in the JavaScript specification that describes how it works at the lowest level. For instance`[[Get]]`, the internal method to read a property, `[[Set]]`, the internal method to write a property, and so on. These methods are only used in the specification, we can't call them directly by name.
49
+
Per molte operazioni sugli oggetti, esiste un cosidetto "metodo interno" nella specifiche JavaScript che ne descrive il funzionamento a basso livello. Ad esempio`[[Get]]`, il metodo interno per la lettura delle proprietà, e `[[Set]]`, il metodo interno per la scrittura delle proprietà, e così via. Questi metodi vengono utilizzati solamente nelle specifiche, non possiamo invocarli direttamente utilizzandone il nome.
51
50
52
-
Proxy traps intercept invocations of these methods. They are listed in the [Proxy specification](https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots)and in the table below.
51
+
Le trappole "proxy" intercettano le invocazioni di questi metodi. Queste vengono elencate nelle[specifiche Proxy](https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots)e nella tabella sottostante.
53
52
54
-
For every internal method, there's a trap in this table: the name of the method that we can add to the `handler`parameter of `new Proxy`to intercept the operation:
53
+
Per ogni metodo interno, esiste una "trappola" in questa tabella: il nome del metodo che possiamo aggiungere al parametro `handler`del `new Proxy`per interecettare l'operazione:
JavaScript enforces some invariants -- conditions that must be fulfilled by internal methods and traps.
71
+
```warn header="Invarianti"
72
+
JavaScript applica alcune invarianti, ovvero condizioni che devono essere soddisfatte da metodi interni e "trappole".
74
73
75
-
Most of them are for return values:
76
-
- `[[Set]]` must return `true` if the value was written successfully, otherwise `false`.
77
-
- `[[Delete]]` must return `true` if the value was deleted successfully, otherwise `false`.
78
-
- ...and so on, we'll see more in examples below.
74
+
Molte di quest sono per i valori di ritorno:
75
+
- `[[Set]]` deve tornare `true` se il valore è stato scritto con successo, altrimenti ritorna `false`.
76
+
- `[[Delete]]` deve tornare `true` se il valore è stato rimosso con successo, altrimenti ritorna `false`.
77
+
- ...E così via, vedremo più esempi sotto.
79
78
80
-
There are some other invariants, like:
81
-
- `[[GetPrototypeOf]]`, applied to the proxy object must return the same value as `[[GetPrototypeOf]]` applied to the proxy object's target object. In other words, reading prototype of a proxy must always return the prototype of the target object.
79
+
Esistono anche altre invarianti, come:
80
+
- `[[GetPrototypeOf]]`, applicata all'oggetto proxy, il quale deve ritornare lo stesso valore di `[[GetPrototypeOf]]` che sarebbe ritornato dall'oggetto target. In altre parole, la lettura del prototype del proxy deve sempre ritornare il prototype dell'oggetto target.
82
81
83
-
Traps can intercept these operations, but they must follow these rules.
82
+
Le "trappole" possono intercettare queste operazioni, ma devono seguire le regole viste.
84
83
85
-
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 you're not doing something weird.
84
+
Le invaraianti assicurano che le funzionalità di linguaggio si comportino in maniera corretta e consistente. La lista completa delle invarianti è disponibile [nelle specifiche](https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots). Probabilmente non le violerai, a meno ché tu non stia facendo qualcosa di strano.
86
85
```
87
86
88
-
Let's see how that works in practical examples.
87
+
Vediamo come funzionano con esempi pratici.
89
88
90
-
## Default value with "get" trap
89
+
## Valore di default con la trappola "get"
91
90
92
-
The most common traps are for reading/writing properties.
91
+
La maggior parte delle "trappole" sono dedicate alla lettura/scrittura di proprietà.
93
92
94
-
To intercept reading, the `handler`should have a method`get(target, property, receiver)`.
93
+
Per intercettare la lettura, l'`handler`dovrebbe possedere un metodo`get(target, property, receiver)`.
95
94
96
-
It triggers when a property is read, with following arguments:
95
+
Verrà innescato quando una proprietà verrà letta, con i seguenti argomenti:
97
96
98
-
-`target` -- is the target object, the one passed as the first argument to`new Proxy`,
99
-
-`property` -- property name,
100
-
-`receiver` -- if the target property is a getter, then`receiver`is the object that's going to be used as `this` in its call. Usually that's the `proxy`object itself (or an object that inherits from it, if we inherit from proxy). Right now we don't need this argument, so it will be explained in more detail later.
97
+
-`target` -- è l'oggetto target, quello fornito come primo argomento a`new Proxy`,
98
+
-`property` -- nome della proprietà,
99
+
-`receiver` -- se la proprietà target è un getter, allora`receiver`sarà l'oggetto che verrà utilizzato come `this` in questa chiamata. Solitamente è l'oggetto `proxy`stesso (oppure un oggetto che eredita da esso, se stiamo ereditando dal proxy). Per ora non abbiamo bisogno di questo argomento, quindi lo analizzeremo nel dettagli più avanti.
101
100
102
-
Let's use `get`to implement default values for an object.
101
+
Utilizziamo `get`per implementare i valore di default di un oggetto.
103
102
104
-
We'll make a numeric array that returns `0`for nonexistent values.
103
+
Costruiremo un array numerico che ritornerà `0`per valori inesistenti.
105
104
106
-
Usually when one tries to get a non-existing array item, they get`undefined`, but we'll wrap a regular array into the proxy that traps reading and returns`0`if there's no such property:
105
+
Soltiamente, quando si prova ad accedere ad una elemento non esistente di un array, si ottiene`undefined`, ma noi costruiremo un proxy di un array che ritorna`0`nel caso in cui la prorpietà non esistesse:
107
106
108
107
```js run
109
108
let numbers = [0, 1, 2];
@@ -113,22 +112,22 @@ numbers = new Proxy(numbers, {
113
112
if (prop in target) {
114
113
return target[prop];
115
114
} else {
116
-
return0; //default value
115
+
return0; //valore di default
117
116
}
118
117
}
119
118
});
120
119
121
120
*!*
122
121
alert( numbers[1] ); // 1
123
-
alert( numbers[123] ); // 0 (no such item)
122
+
alert( numbers[123] ); // 0 (elemento non esistente)
124
123
*/!*
125
124
```
126
125
127
-
As we can see, it's quite easy to do with a `get` trap.
126
+
Come possiamo vedere, è molto semplice da fare con una "trappola" `get`.
128
127
129
-
We can use`Proxy`to implement any logic for "default" values.
128
+
Possiamo utilizzare un`Proxy`per implementare una logica per i valore i valori di "default".
130
129
131
-
Imagine we have a dictionary, with phrases and their translations:
130
+
Immaginiamo di avere un dizionario, contenente i termini e le rispettive traduzioni:
Right now, if there's no phrase, reading from `dictionary`returns`undefined`. But in practice, leaving a phrase untranslated is usually better than `undefined`. So let's make it return an untranslated phrase in that case instead of`undefined`.
142
+
Attualmente, se non esiste un termine, la lettura dal `dictionary`ritorna`undefined`. Ma nella pratica, mantenere un termine non tradotto è generalmente meglio di `undefined`. Quindi facciamo in modo che ritorni il termine non tradotto piuttosto di`undefined`.
144
143
145
144
To achieve that, we'll wrap `dictionary` in a proxy that intercepts reading operations:
0 commit comments