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
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`.
142
+
Attualmente, se non esiste un termine, la lettura dal `dictionary` ritorna `undefined`. Ma nella pratica, ritornare un termine non tradotto è generalmente meglio di `undefined`. Quindi facciamo in modo che ritorni il termine non tradotto piuttosto di `undefined`.
143
143
144
-
To achieve that, we'll wrap `dictionary`in a proxy that intercepts reading operations:
144
+
Per farlo, costruiremo un contenitore per `dictionary`con un proxy che interecetterà le operazioni di lettura:
145
145
146
146
```js run
147
147
let dictionary = {
@@ -151,58 +151,58 @@ let dictionary = {
151
151
152
152
dictionary =newProxy(dictionary, {
153
153
*!*
154
-
get(target, phrase) { //intercept reading a property from dictionary
154
+
get(target, phrase) { //interecetta la lettura di una proprietà dal dictionary
155
155
*/!*
156
-
if (phrase in target) { //if we have it in the dictionary
157
-
return target[phrase]; //return the translation
156
+
if (phrase in target) { //se è contenuto nel dictionary
157
+
return target[phrase]; //ritorna la traduzione
158
158
} else {
159
-
//otherwise, return the non-translated phrase
159
+
//altrimenti, ritorna il termine non tradotto
160
160
return phrase;
161
161
}
162
162
}
163
163
});
164
164
165
-
//Look up arbitrary phrases in the dictionary!
166
-
//At worst, they're not translated.
165
+
//Cerchiamo un termine casuale nel dictionary!
166
+
//Nel peggiore dei casi, questo non sarà tradotto.
167
167
alert( dictionary['Hello'] ); // Hola
168
168
*!*
169
-
alert( dictionary['Welcome to Proxy']); //Welcome to Proxy (no translation)
169
+
alert( dictionary['Welcome to Proxy']); //BeWelcome to Proxy (nessuna traduzione)
170
170
*/!*
171
171
```
172
172
173
173
````smart
174
-
Please note how the proxy overwrites the variable:
174
+
Da notare come il proxy sovrascrive la variabile:
175
175
176
176
```js
177
177
dictionary = new Proxy(dictionary, ...);
178
178
```
179
179
180
-
The proxy should totally replace the target object everywhere. No one should ever reference the target object after it got proxied. Otherwise it's easy to mess up.
180
+
Il proxy dovrebbe rimpiazzare completamente il target ovunque. Nessuno dovrebbe più fare riferimento all'oggetto target una volta che questo ne è stato costruito un proxy. Altrimenti diventa molto facile commettere errori.
181
181
````
182
182
183
-
## Validation with "set" trap
183
+
## Validazione con la trappola "set"
184
184
185
-
Let's say we want an array exclusively for numbers. If a value of another type is added, there should be an error.
185
+
Ipotizziamo di volere un array di soli numeri. Se viene aggiunto un valore di un altro tipo, questo dovrebbe generare un errore.
186
186
187
-
The `set`trap triggers when a property is written.
187
+
La "trappola" `set`si innesca quando si accede in scrittura ad una proprietà.
188
188
189
189
`set(target, property, value, receiver)`:
190
190
191
-
-`target` -- is the target object, the one passed as the first argument to`new Proxy`,
192
-
-`property` -- property name,
193
-
-`value` -- property value,
194
-
-`receiver` -- similar to `get` trap, matters only for setter properties.
191
+
-`target` -- rappresenta l'oggetto target, quello fornito come primo argomento a`new Proxy`,
192
+
-`property` -- il nome della proprietà,
193
+
-`value` -- il valore della proprietà,
194
+
-`receiver` -- similmente alla trappola `get`, ha importanza solamente per le proprietà di tipo setter.
195
195
196
-
The `set`trap should return `true`if setting is successful, and `false`otherwise (triggers`TypeError`).
196
+
La trappola `set`dovrebbe ritornare `true`se è stata imposta correttamete, `false`altrimenti (innescando`TypeError`).
numbers.push("test"); // TypeError ('set' on proxy returned false)
221
+
numbers.push("test"); // TypeError ('set' di proxy ha ritornato false)
222
222
*/!*
223
223
224
224
alert("This line is never reached (error in the line above)");
225
225
```
226
226
227
-
Please note: the built-in functionality of arrays is still working! Values are added by `push`. The `length`property auto-increases when values are added. Our proxy doesn't break anything.
227
+
Da notare: la funzionalità interna degli array integrati continuano a funzionare! I valori vengono aggiunti tramite `push`. La proprietà `length`viene auto-incrementata quando i valori vengono aggiunti. Il nostro proxy non rompe nulla.
228
228
229
-
We don't have to override value-adding array methods like `push`and`unshift`, and so on, to add checks in there, because internally they use the `[[Set]]`operation that's intercepted by the proxy.
229
+
Non dobbiamo sovrascrivere il metodo di aggiunta valori agli array come `push`e`unshift`, e così via, per aggiungere i controlli in questi casi, poiché questi internamente utilizzano operazioni di `[[Set]]`che verranno intercettate dal proxy.
230
230
231
-
So the code is clean and concise.
231
+
In questo modo il codice rimane pulito e conciso.
232
232
233
-
```warn header="Don't forget to return`true`"
234
-
As said above, there are invariants to be held.
233
+
```warn header="Non dimenticate di ritornare`true`"
234
+
Come detto sopra, vanno tenute in considerazione le invarianti.
235
235
236
-
For `set`, it must return`true`for a successful write.
236
+
Nel caso di `set`, questo deve ritornare`true`per scritture avvenute con successo.
237
237
238
-
If we forget to do it or return any falsy value, the operation triggers`TypeError`.
238
+
Se ci dimentichiamo di farlo o ritorniamo qualsiasi altro valore, l'operazione innescherà`TypeError`.
239
239
```
240
240
241
-
## Iteration with "ownKeys" and "getOwnPropertyDescriptor"
241
+
## Iterazione con "ownKeys" e "getOwnPropertyDescriptor"
242
242
243
-
`Object.keys`, `for..in` loop and most other methods that iterate over object properties use `[[OwnPropertyKeys]]` internal method (intercepted by `ownKeys` trap) to get a list of properties.
243
+
I cicli `Object.keys`, `for..in` e molti altri metodi che iterano sulle proprietà degli oggetti utilizzano il metodo interno `[[OwnPropertyKeys]]` (intercettate dalla trappola `ownKeys`) per ottenere la lista delle proprietà.
- `Object.getOwnPropertySymbols(obj)` returns symbol keys.
248
-
- `Object.keys/values()` returns non-symbol keys/values with `enumerable` flag (property flags were explained in the article <info:property-descriptors>).
249
-
- `for..in` loops over non-symbol keys with `enumerable` flag, and also prototype keys.
245
+
Questi metodi si distinguono per alcuni dettagli:
246
+
- `Object.getOwnPropertyNames(obj)` ritorna le chiavi non-symbol.
247
+
- `Object.getOwnPropertySymbols(obj)` ritorna le chiavi symbol.
248
+
- `Object.keys/values()` ritorna coppie keys/values non-symbol, con la flag `enumerable` (le flag sono state spiegate nell'articolo <info:property-descriptors>).
249
+
- `for..in` cicla su chiavi non-symbol, con la flag `enumerable`, ed anche sullle chiavi del prototype.
250
250
251
-
...But all of them start with that list.
251
+
...Ma tutti questi, incominciamo dalla stessa lista.
252
252
253
-
In the example below we use `ownKeys` trap to make `for..in` loop over `user`, and also `Object.keys` and `Object.values`, to skip properties starting with an underscore `_`:
253
+
Nell'esempio sotto, utilizziamo la trappola `ownKeys` per far sì che `for..in` cicli su `user`, `Object.keys` e `Object.values`, saltando le proprietà il cui nome incomincia con un underscore `_`:
254
254
255
255
```js run
256
256
let user = {
@@ -267,17 +267,17 @@ user = new Proxy(user, {
267
267
}
268
268
});
269
269
270
-
// "ownKeys" filters out _password
270
+
// "ownKeys" filtra _password, saltandolo
271
271
for(let key in user) alert(key); // name, then: age
272
272
273
-
// same effect on these methods:
273
+
// abbiamo lo stesso effetto in questi meotodi:
274
274
alert( Object.keys(user) ); // name,age
275
275
alert( Object.values(user) ); // John,30
276
276
```
277
277
278
-
So far, it works.
278
+
Finora, funziona.
279
279
280
-
Although, if we return a key that doesn't exist in the object, `Object.keys`won't list it:
280
+
Anche se, nel caso in cui ritornassimo una chiave che non esiste nell'oggetto, `Object.keys`non la elencherà:
281
281
282
282
```js run
283
283
let user = { };
@@ -293,25 +293,25 @@ user = new Proxy(user, {
293
293
alert( Object.keys(user) ); // <empty>
294
294
```
295
295
296
-
Why? The reason is simple: `Object.keys`returns only properties with the `enumerable` flag. To check for it, it calls the internal method `[[GetOwnProperty]]` for every property to get [its descriptor](info:property-descriptors). And here, as there's no property, its descriptor is empty, no `enumerable` flag, so it's skipped.
296
+
Perché? La motivazione è semplice: `Object.keys`ritorna solamente le prorpietà con la flag `enumerable`. Per verificarlo, invoca il metodo interno `[[GetOwnProperty]]`su ogni proprietà per ottenere [i suoi descrittori](info:property-descriptors). E in questo caso, poiché non ci sono proprietà, i descrittori sono vuoti, non abbiamo alcuna flag `enumerable`, quindi questa verrà saltata.
297
297
298
-
For `Object.keys`to return a property, we need it to either exist in the object, with the `enumerable` flag, or we can intercept calls to `[[GetOwnProperty]]` (the trap `getOwnPropertyDescriptor` does it), and return a descriptor with`enumerable: true`.
298
+
Per far sì che `Object.keys`ritorni una proprietà, è necessario che, o questa esiste nell'oggetto con la flag `enumerable`, oppure possiamo intercettare l'invocazione di `[[GetOwnProperty]]` (tramite la trappola `getOwnPropertyDescriptor`), e ritornare un descrittore con`enumerable: true`.
299
299
300
-
Here's an example of that:
300
+
Qui vediamo un esempio:
301
301
302
302
```js run
303
303
let user = { };
304
304
305
305
user =newProxy(user, {
306
-
ownKeys(target) { //called once to get a list of properties
306
+
ownKeys(target) { //invocata una volta per ottenere una lista delle proprietà
307
307
return ['a', 'b', 'c'];
308
308
},
309
309
310
-
getOwnPropertyDescriptor(target, prop) { //called for every property
310
+
getOwnPropertyDescriptor(target, prop) { //invocata per ogni proprietà
311
311
return {
312
312
enumerable:true,
313
313
configurable:true
314
-
/* ...other flags, probable "value:..." */
314
+
/* ...altre flag, tra cui "value:..." */
315
315
};
316
316
}
317
317
@@ -320,13 +320,13 @@ user = new Proxy(user, {
320
320
alert( Object.keys(user) ); // a, b, c
321
321
```
322
322
323
-
Let's note once again: we only need to intercept `[[GetOwnProperty]]`if the property is absent in the object.
323
+
Ripetiamolo una volta ancora: è sufficiente intercettare `[[GetOwnProperty]]`se la proprietà non è presente nell'oggetto.
324
324
325
-
## Protected properties with "deleteProperty" and other traps
325
+
## Le proprietà protette da "deleteProperty" e altre trappole
326
326
327
-
There's a widespread convention that properties and methods prefixed by an underscore `_` are internal. They shouldn't be accessed from outside the object.
327
+
Esiste una convenzione piuttosto diffusa, in cui le proprietà e i metodi il cui nome ha come suffisso un underscore `_`, sono da considerarsi interne. Non dovrebbero quindi essere accedute dall'esterno dell'oggetto.
328
328
329
-
Technically that's possible though:
329
+
Anche se riamane tecnicamente possibile accedervi:
330
330
331
331
```js run
332
332
let user = {
@@ -337,15 +337,15 @@ let user = {
337
337
alert(user._password); // secret
338
338
```
339
339
340
-
Let's use proxies to prevent any access to properties starting with`_`.
340
+
Possiamo utilizzare un proxy per rendere inaccessibile le proprietà che iniziano con `_`.
341
341
342
-
We'll need the traps:
343
-
-`get`to throw an error when reading such property,
344
-
-`set`to throw an error when writing,
345
-
-`deleteProperty`to throw an error when deleting,
346
-
-`ownKeys`to exclude properties starting with `_`from`for..in`and methods like`Object.keys`.
342
+
Avremo bisogno delle seguenti trappole:
343
+
-`get`per ritornare un errore nel tentativo di accedere a questa proprietà,
344
+
-`set`per ritornare un errore nel tentativo di scrittura,
345
+
-`deleteProperty`per ritornare un errore nel tentativo di rimozione,
346
+
-`ownKeys`per escludere le proprietà che iniziano con `_`da`for..in`ed altri metodi come`Object.keys`.
347
347
348
-
Here's the code:
348
+
Vediamo il codice:
349
349
350
350
```js run
351
351
let user = {
@@ -364,7 +364,7 @@ user = new Proxy(user, {
364
364
return (typeof value ==='function') ?value.bind(target) : value; // (*)
0 commit comments