Skip to content

Commit 42b241f

Browse files
committed
translation progress
1 parent fa9dbb1 commit 42b241f

File tree

1 file changed

+75
-75
lines changed

1 file changed

+75
-75
lines changed

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

Lines changed: 75 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -139,9 +139,9 @@ alert( dictionary['Hello'] ); // Hola
139139
alert( dictionary['Welcome'] ); // undefined
140140
```
141141

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

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

146146
```js run
147147
let dictionary = {
@@ -151,58 +151,58 @@ let dictionary = {
151151

152152
dictionary = new Proxy(dictionary, {
153153
*!*
154-
get(target, phrase) { // intercept reading a property from dictionary
154+
get(target, phrase) { // interecetta la lettura di una proprietà dal dictionary
155155
*/!*
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
158158
} else {
159-
// otherwise, return the non-translated phrase
159+
// altrimenti, ritorna il termine non tradotto
160160
return phrase;
161161
}
162162
}
163163
});
164164

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.
167167
alert( dictionary['Hello'] ); // Hola
168168
*!*
169-
alert( dictionary['Welcome to Proxy']); // Welcome to Proxy (no translation)
169+
alert( dictionary['Welcome to Proxy']); // BeWelcome to Proxy (nessuna traduzione)
170170
*/!*
171171
```
172172

173173
````smart
174-
Please note how the proxy overwrites the variable:
174+
Da notare come il proxy sovrascrive la variabile:
175175
176176
```js
177177
dictionary = new Proxy(dictionary, ...);
178178
```
179179
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.
181181
````
182182

183-
## Validation with "set" trap
183+
## Validazione con la trappola "set"
184184

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

187-
The `set` trap triggers when a property is written.
187+
La "trappola" `set` si innesca quando si accede in scrittura ad una proprietà.
188188

189189
`set(target, property, value, receiver)`:
190190

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

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

198-
Let's use it to validate new values:
198+
Utilizziamola per validare un nuovo valore:
199199

200200
```js run
201201
let numbers = [];
202202

203203
numbers = new Proxy(numbers, { // (*)
204204
*!*
205-
set(target, prop, val) { // to intercept property writing
205+
set(target, prop, val) { // per intercettare la scrittura di proprietà
206206
*/!*
207207
if (typeof val == 'number') {
208208
target[prop] = val;
@@ -213,44 +213,44 @@ numbers = new Proxy(numbers, { // (*)
213213
}
214214
});
215215

216-
numbers.push(1); // added successfully
217-
numbers.push(2); // added successfully
216+
numbers.push(1); // aggiunta con successo
217+
numbers.push(2); // aggiunta con successo
218218
alert("Length is: " + numbers.length); // 2
219219

220220
*!*
221-
numbers.push("test"); // TypeError ('set' on proxy returned false)
221+
numbers.push("test"); // TypeError ('set' di proxy ha ritornato false)
222222
*/!*
223223

224224
alert("This line is never reached (error in the line above)");
225225
```
226226

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

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

231-
So the code is clean and concise.
231+
In questo modo il codice rimane pulito e conciso.
232232

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

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

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`.
239239
```
240240
241-
## Iteration with "ownKeys" and "getOwnPropertyDescriptor"
241+
## Iterazione con "ownKeys" e "getOwnPropertyDescriptor"
242242
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à.
244244
245-
Such methods differ in details:
246-
- `Object.getOwnPropertyNames(obj)` returns non-symbol keys.
247-
- `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.
250250
251-
...But all of them start with that list.
251+
...Ma tutti questi, incominciamo dalla stessa lista.
252252
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 `_`:
254254
255255
```js run
256256
let user = {
@@ -267,17 +267,17 @@ user = new Proxy(user, {
267267
}
268268
});
269269
270-
// "ownKeys" filters out _password
270+
// "ownKeys" filtra _password, saltandolo
271271
for(let key in user) alert(key); // name, then: age
272272
273-
// same effect on these methods:
273+
// abbiamo lo stesso effetto in questi meotodi:
274274
alert( Object.keys(user) ); // name,age
275275
alert( Object.values(user) ); // John,30
276276
```
277277

278-
So far, it works.
278+
Finora, funziona.
279279

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à:
281281

282282
```js run
283283
let user = { };
@@ -293,25 +293,25 @@ user = new Proxy(user, {
293293
alert( Object.keys(user) ); // <empty>
294294
```
295295

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

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

300-
Here's an example of that:
300+
Qui vediamo un esempio:
301301

302302
```js run
303303
let user = { };
304304

305305
user = new Proxy(user, {
306-
ownKeys(target) { // called once to get a list of properties
306+
ownKeys(target) { // invocata una volta per ottenere una lista delle proprietà
307307
return ['a', 'b', 'c'];
308308
},
309309

310-
getOwnPropertyDescriptor(target, prop) { // called for every property
310+
getOwnPropertyDescriptor(target, prop) { // invocata per ogni proprietà
311311
return {
312312
enumerable: true,
313313
configurable: true
314-
/* ...other flags, probable "value:..." */
314+
/* ...altre flag, tra cui "value:..." */
315315
};
316316
}
317317

@@ -320,13 +320,13 @@ user = new Proxy(user, {
320320
alert( Object.keys(user) ); // a, b, c
321321
```
322322

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

325-
## Protected properties with "deleteProperty" and other traps
325+
## Le proprietà protette da "deleteProperty" e altre trappole
326326

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

329-
Technically that's possible though:
329+
Anche se riamane tecnicamente possibile accedervi:
330330

331331
```js run
332332
let user = {
@@ -337,15 +337,15 @@ let user = {
337337
alert(user._password); // secret
338338
```
339339

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 `_`.
341341

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

348-
Here's the code:
348+
Vediamo il codice:
349349

350350
```js run
351351
let user = {
@@ -364,7 +364,7 @@ user = new Proxy(user, {
364364
return (typeof value === 'function') ? value.bind(target) : value; // (*)
365365
},
366366
*!*
367-
set(target, prop, val) { // to intercept property writing
367+
set(target, prop, val) { // per intercettare la scrittura delle proprietà
368368
*/!*
369369
if (prop.startsWith('_')) {
370370
throw new Error("Access denied");
@@ -374,7 +374,7 @@ user = new Proxy(user, {
374374
}
375375
},
376376
*!*
377-
deleteProperty(target, prop) { // to intercept property deletion
377+
deleteProperty(target, prop) { // per intercettare la rimozione delle proprietà
378378
*/!*
379379
if (prop.startsWith('_')) {
380380
throw new Error("Access denied");
@@ -384,32 +384,32 @@ user = new Proxy(user, {
384384
}
385385
},
386386
*!*
387-
ownKeys(target) { // to intercept property list
387+
ownKeys(target) { // per intercettare lo scorrimento delle proprietà
388388
*/!*
389389
return Object.keys(target).filter(key => !key.startsWith('_'));
390390
}
391391
});
392392

393-
// "get" doesn't allow to read _password
393+
// "get" non consente di leggere _password
394394
try {
395-
alert(user._password); // Error: Access denied
395+
alert(user._password); // Errore: Access denied
396396
} catch(e) { alert(e.message); }
397397

398-
// "set" doesn't allow to write _password
398+
// "set" non consente di scrivere _password
399399
try {
400-
user._password = "test"; // Error: Access denied
400+
user._password = "test"; // Errore: Access denied
401401
} catch(e) { alert(e.message); }
402402

403-
// "deleteProperty" doesn't allow to delete _password
403+
// "deleteProperty" non consente di rimuovere _password
404404
try {
405-
delete user._password; // Error: Access denied
405+
delete user._password; // Errore: Access denied
406406
} catch(e) { alert(e.message); }
407407

408-
// "ownKeys" filters out _password
408+
// "ownKeys" rimuove _password dal ciclo
409409
for(let key in user) alert(key); // name
410410
```
411411

412-
Please note the important detail in the `get` trap, in the line `(*)`:
412+
Da notare un dettaglio importante nella trappola `get`, nella riga `(*)`:
413413

414414
```js
415415
get(target, prop) {
@@ -421,15 +421,15 @@ get(target, prop) {
421421
}
422422
```
423423

424-
Why do we need a function to call `value.bind(target)`?
424+
Perché abbiamo bisogno di una funzione per invocare `value.bind(target)`?
425425

426-
The reason is that object methods, such as `user.checkPassword()`, must be able to access `_password`:
426+
La motivazione è che i metodi dell'oggetto, come `user.checkPassword()`, devono essere in grado di accedere a `_password`:
427427

428428
```js
429429
user = {
430430
// ...
431431
checkPassword(value) {
432-
// object method must be able to read _password
432+
// i metodi dell'oggetto devono essere in grado di leggere _password
433433
return value === this._password;
434434
}
435435
}

0 commit comments

Comments
 (0)