Skip to content

Commit fa9dbb1

Browse files
committed
transalte first part
1 parent 131dfcf commit fa9dbb1

File tree

1 file changed

+58
-59
lines changed

1 file changed

+58
-59
lines changed

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

Lines changed: 58 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,65 @@
1-
# Proxy and Reflect
1+
# Proxy e Reflect
22

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.
44

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.
66

77
## Proxy
88

9-
The syntax:
9+
La sintassi:
1010

1111
```js
1212
let proxy = new Proxy(target, handler)
1313
```
1414

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.
1717

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":
2120

2221
```js run
2322
let target = {};
24-
let proxy = new Proxy(target, {}); // empty handler
23+
let proxy = new Proxy(target, {}); // handler vuoto
2524

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!
2827

29-
alert(proxy.test); // 5, we can read it from proxy too (2)
28+
alert(proxy.test); // 5, possiamo leggerla anche dal proxy (2)
3029

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)
3231
```
3332

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`.
3534

36-
1. A writing operation `proxy.test=` sets the value on `target`.
37-
2. A reading operation `proxy.test` returns the value from `target`.
38-
3. Iteration over `proxy` returns values from `target`.
35+
1. Un'operazione di scrittura `proxy.test=` imposta il valore su `target`.
36+
2. Un'operazione di lettura `proxy.test` ritorna iil valore da `target`.
37+
3. L'iterazione su `proxy` ritorna valori da `target`.
3938

40-
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`.
4140

4241
![](proxy.svg)
4342

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`.
4544

46-
To activate more capabilities, let's add traps.
45+
Per attivare più funzionalità, aggiungiamo qualche "trappola".
4746

48-
What can we intercept with them?
47+
Cosa possiamo intercettare?
4948

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.
5150

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.
5352

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:
5554

56-
| Internal Method | Handler Method | Triggers when... |
55+
| Metodo Interno | Handler | Innescato quando... |
5756
|-----------------|----------------|-------------|
58-
| `[[Get]]` | `get` | reading a property |
59-
| `[[Set]]` | `set` | writing to a property |
60-
| `[[HasProperty]]` | `has` | `in` operator |
61-
| `[[Delete]]` | `deleteProperty` | `delete` operator |
62-
| `[[Call]]` | `apply` | function call |
63-
| `[[Construct]]` | `construct` | `new` operator |
57+
| `[[Get]]` | `get` | lettura di un proprietà |
58+
| `[[Set]]` | `set` | scrittura di un proprietà |
59+
| `[[HasProperty]]` | `has` | operatore `in` |
60+
| `[[Delete]]` | `deleteProperty` | operatore `delete` |
61+
| `[[Call]]` | `apply` | invocazione di funzione |
62+
| `[[Construct]]` | `construct` | operatore `new` |
6463
| `[[GetPrototypeOf]]` | `getPrototypeOf` | [Object.getPrototypeOf](mdn:/JavaScript/Reference/Global_Objects/Object/getPrototypeOf) |
6564
| `[[SetPrototypeOf]]` | `setPrototypeOf` | [Object.setPrototypeOf](mdn:/JavaScript/Reference/Global_Objects/Object/setPrototypeOf) |
6665
| `[[IsExtensible]]` | `isExtensible` | [Object.isExtensible](mdn:/JavaScript/Reference/Global_Objects/Object/isExtensible) |
@@ -69,41 +68,41 @@ For every internal method, there's a trap in this table: the name of the method
6968
| `[[GetOwnProperty]]` | `getOwnPropertyDescriptor` | [Object.getOwnPropertyDescriptor](mdn:/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor), `for..in`, `Object.keys/values/entries` |
7069
| `[[OwnPropertyKeys]]` | `ownKeys` | [Object.getOwnPropertyNames](mdn:/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames), [Object.getOwnPropertySymbols](mdn:/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols), `for..in`, `Object.keys/values/entries` |
7170

72-
```warn header="Invariants"
73-
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".
7473
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.
7978
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.
8281
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.
8483
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.
8685
```
8786

88-
Let's see how that works in practical examples.
87+
Vediamo come funzionano con esempi pratici.
8988

90-
## Default value with "get" trap
89+
## Valore di default con la trappola "get"
9190

92-
The most common traps are for reading/writing properties.
91+
La maggior parte delle "trappole" sono dedicate alla lettura/scrittura di proprietà.
9392

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)`.
9594

96-
It triggers when a property is read, with following arguments:
95+
Verrà innescato quando una proprietà verrà letta, con i seguenti argomenti:
9796

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.
101100

102-
Let's use `get` to implement default values for an object.
101+
Utilizziamo `get` per implementare i valore di default di un oggetto.
103102

104-
We'll make a numeric array that returns `0` for nonexistent values.
103+
Costruiremo un array numerico che ritornerà `0` per valori inesistenti.
105104

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:
107106

108107
```js run
109108
let numbers = [0, 1, 2];
@@ -113,22 +112,22 @@ numbers = new Proxy(numbers, {
113112
if (prop in target) {
114113
return target[prop];
115114
} else {
116-
return 0; // default value
115+
return 0; // valore di default
117116
}
118117
}
119118
});
120119

121120
*!*
122121
alert( numbers[1] ); // 1
123-
alert( numbers[123] ); // 0 (no such item)
122+
alert( numbers[123] ); // 0 (elemento non esistente)
124123
*/!*
125124
```
126125

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`.
128127

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".
130129

131-
Imagine we have a dictionary, with phrases and their translations:
130+
Immaginiamo di avere un dizionario, contenente i termini e le rispettive traduzioni:
132131

133132
```js run
134133
let dictionary = {
@@ -140,7 +139,7 @@ alert( dictionary['Hello'] ); // Hola
140139
alert( dictionary['Welcome'] ); // undefined
141140
```
142141

143-
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`.
144143

145144
To achieve that, we'll wrap `dictionary` in a proxy that intercepts reading operations:
146145

0 commit comments

Comments
 (0)