Skip to content

Commit 67a15a5

Browse files
authored
Merge pull request #199 from longo-andrea/article/getters-setters
Property getters and setters
2 parents a5945eb + 7f714de commit 67a15a5

File tree

1 file changed

+46
-46
lines changed
  • 1-js/07-object-properties/02-property-accessors

1 file changed

+46
-46
lines changed

1-js/07-object-properties/02-property-accessors/article.md

Lines changed: 46 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,31 @@
11

2-
# Property getters and setters
2+
# Proprietà getters e setters
33

4-
There are two kinds of object properties.
4+
Esistono due tipi di proprietà per gli oggetti.
55

6-
The first kind is *data properties*. We already know how to work with them. All properties that we've been using until now were data properties.
6+
Il primo tipo sono le *data properties* (proprietà di tipo "dato"). Sappiamo già come utilizzarle, poiché tutte le proprietà viste fino ad ora erano *date properties*.
77

8-
The second type of properties is something new. It's *accessor properties*. They are essentially functions that execute on getting and setting a value, but look like regular properties to an external code.
8+
Il secondo tipo di proprietà è qualcosa di nuovo. Sono definite *accessor properties* (proprietà accessorie). Sono essenzialmente funzioni che vengono eseguite quando viene letto o impostato un valore, ma al codice esterno appaiono come normali proprietà.
99

10-
## Getters and setters
10+
## Getters e setters
1111

12-
Accessor properties are represented by "getter" and "setter" methods. In an object literal they are denoted by `get` and `set`:
12+
Le *accessor properties* sono rappresentate dai metodi *"getter"* e *"setter"*. In un *object literal* vengono indicate da *`get`* e *`set`*:
1313

1414
```js
1515
let obj = {
1616
*!*get propName()*/!* {
17-
// getter, the code executed on getting obj.propName
17+
// getter, il codice eseguito per ottenere obj.propName
1818
},
1919

2020
*!*set propName(value)*/!* {
21-
// setter, the code executed on setting obj.propName = value
21+
// setter, il codice eseguito per impostare il valore di obj.propName = value
2222
}
2323
};
2424
```
2525

26-
The getter works when `obj.propName` is read, the setter -- when it is assigned.
26+
La proprietà *getter* viene eseguita quando `obj.propName` viene letto, la proprietà *setter*, invece, quando viene assegnato.
2727

28-
For instance, we have a `user` object with `name` and `surname`:
28+
Ad esempio, abbiamo un oggetto `user` con le proprietà `name` e `surname`:
2929

3030
```js
3131
let user = {
@@ -34,7 +34,7 @@ let user = {
3434
};
3535
```
3636

37-
Now we want to add a `fullName` property, that should be `"John Smith"`. Of course, we don't want to copy-paste existing information, so we can implement it as an accessor:
37+
Ora vogliamo aggiungere una proprietà `fullName`, che dovrebbe valere `"John Smith"`. Ovviamente vorremmo evitare di copiare ed incollare informazioni già esistenti, quindi possiamo implementare questa funzionalità tramite un *accessor*:
3838

3939
```js run
4040
let user = {
@@ -53,9 +53,9 @@ alert(user.fullName); // John Smith
5353
*/!*
5454
```
5555

56-
From the outside, an accessor property looks like a regular one. That's the idea of accessor properties. We don't *call* `user.fullName` as a function, we *read* it normally: the getter runs behind the scenes.
56+
Vista esternamente, una *accessor property* è del tutto simile ad una normale proprietà, è questa l'idea che sta dietro alle *accessor properties*. Non *invochiamo* `user.fullName` come una normale funzione, ma la *leggiamo* come una normale proprietà: in questo caso il *getter* sta lavorando per noi.
5757

58-
As of now, `fullName` has only a getter. If we attempt to assign `user.fullName=`, there will be an error:
58+
Per ora, `fullName` possiede un solo getter. Se provassimo ad assegnare `user.fullName=`, otterremo un errore:
5959

6060
```js run
6161
let user = {
@@ -65,11 +65,11 @@ let user = {
6565
};
6666

6767
*!*
68-
user.fullName = "Test"; // Error (property has only a getter)
68+
user.fullName = "Test"; // Error (la proprietà possiede solo un getter)
6969
*/!*
7070
```
7171

72-
Let's fix it by adding a setter for `user.fullName`:
72+
Aggiungiamo quindi un *setter* per `user.fullName`:
7373

7474
```js run
7575
let user = {
@@ -87,29 +87,29 @@ let user = {
8787
*/!*
8888
};
8989

90-
// set fullName is executed with the given value.
90+
// set fullName viene eseguito con i valori forniti
9191
user.fullName = "Alice Cooper";
9292

9393
alert(user.name); // Alice
9494
alert(user.surname); // Cooper
9595
```
9696

97-
As the result, we have a "virtual" property `fullName`. It is readable and writable.
97+
Come risultato finale, abbiamo un proprietà "virtuale" `fullName`. Che possiamo sia leggere che scrivere.
9898

99-
## Accessor descriptors
99+
## Descrittori degli *accessors*
100100

101-
Descriptors for accessor properties are different from those for data properties.
101+
I descrittori per le *accessor prorperties* sono diversi da quelli per le *data properties*.
102102

103-
For accessor properties, there is no `value` or `writable`, but instead there are `get` and `set` functions.
103+
Per le *accessor properties*, non ci sono `value` o `writable`, ma ci sono invece le funzioni `get` or `set`.
104104

105-
That is, an accessor descriptor may have:
105+
Un descrittore di *accessor properties* può possedere:
106106

107-
- **`get`** -- a function without arguments, that works when a property is read,
108-
- **`set`** -- a function with one argument, that is called when the property is set,
109-
- **`enumerable`** -- same as for data properties,
110-
- **`configurable`** -- same as for data properties.
107+
- **`get`** -- una funzione che non accetta argomenti, che specifica come accedere in lettura ad una proprietà,
108+
- **`set`** -- una funzione con un solo argomento, che specifica come impostare il valore della proprietà,
109+
- **`enumerable`** -- stesso comportamento visto per le *data properties*,
110+
- **`configurable`** -- stesso comportamento visto per le *data properties*.
111111

112-
For instance, to create an accessor `fullName` with `defineProperty`, we can pass a descriptor with `get` and `set`:
112+
Ad esempio, possiamo creare un *accessor* `fullName` con `defineProperty`, passando un *descriptor* con `get` e `set`:
113113

114114
```js run
115115
let user = {
@@ -134,9 +134,9 @@ alert(user.fullName); // John Smith
134134
for(let key in user) alert(key); // name, surname
135135
```
136136

137-
Please note that a property can be either an accessor (has `get/set` methods) or a data property (has a `value`), not both.
137+
Da notare che una proprietà può essere o un *accessor* (con i metodi `get/set`) o una *data property* (con un `value`), ma non entrambe.
138138

139-
If we try to supply both `get` and `value` in the same descriptor, there will be an error:
139+
Se proviamo a fornire sia `get` che `value`, nello stesso *descriptor*, otterremo un errore:
140140

141141
```js run
142142
*!*
@@ -151,11 +151,11 @@ Object.defineProperty({}, 'prop', {
151151
});
152152
```
153153

154-
## Smarter getters/setters
154+
## Getters/setters intelligenti
155155

156-
Getters/setters can be used as wrappers over "real" property values to gain more control over operations with them.
156+
*Getters/setters* possono essere utilizzati come *wrappers* (contenitori) per le proprietà "reali", in questo modo avremo più controllo sulle operazioni di lettura/scrittura.
157157

158-
For instance, if we want to forbid too short names for `user`, we can have a setter `name` and keep the value in a separate property `_name`:
158+
Ad esempio, potremmo vietare nomi troppo brevi per la proprietà `name`, possiamo definire un *setter* `name` e mantenere il valore in una proprietà diversa `_name`:
159159

160160
```js run
161161
let user = {
@@ -175,19 +175,19 @@ let user = {
175175
user.name = "Pete";
176176
alert(user.name); // Pete
177177

178-
user.name = ""; // Name is too short...
178+
user.name = ""; // Il nome è troppo corto...
179179
```
180180

181-
So, the name is stored in `_name` property, and the access is done via getter and setter.
181+
Quindi, il nome viene memorizzato nella prorietà `_name`, e gli accessi vengono effettuati tramite *getter* e *setter*.
182182

183-
Technically, external code is able to access the name directly by using `user._name`. But there is a widely known convention that properties starting with an underscore `"_"` are internal and should not be touched from outside the object.
183+
Tecnicamente, il codice all'esterno potrebbe accedere direttamente al nome utilizzando `user._name`. Ma esiste una convezione molto diffusa che specifica di non utilizzare direttamente le proprietà che iniziano con `"_"`.
184184

185185

186-
## Using for compatibility
186+
## Utilizzato per compatibilità
187187

188-
One of the great uses of accessors is that they allow to take control over a "regular" data property at any moment by replacing it with a getter and a setter and tweak its behavior.
188+
Uno dei principali vantaggi offerti dagli *accessors* è che permettono di migliorare il controllo di una normale *data property* rimpiazzandola con le proprietà *getter* e *setter* e lavorando sul loro comportamento.
189189

190-
Imagine we started implementing user objects using data properties `name` and `age`:
190+
Immaginiamo di inziare ad implementare l'oggetto `user` con le proprietà `name` e `age`°
191191

192192
```js
193193
function User(name, age) {
@@ -200,7 +200,7 @@ let john = new User("John", 25);
200200
alert( john.age ); // 25
201201
```
202202

203-
...But sooner or later, things may change. Instead of `age` we may decide to store `birthday`, because it's more precise and convenient:
203+
...Ma prima o poi, le cose potrebbero cambiare. Invece di `age` potremmo decidere di memorizzare `birthday`, poiché è più preciso e conveniente:
204204

205205
```js
206206
function User(name, birthday) {
@@ -211,21 +211,21 @@ function User(name, birthday) {
211211
let john = new User("John", new Date(1992, 6, 1));
212212
```
213213

214-
Now what to do with the old code that still uses `age` property?
214+
Ora come ci comportiamo con il codice "vecchio" che utilizza ancora la proprietà `age`?
215215

216-
We can try to find all such places and fix them, but that takes time and can be hard to do if that code is used by many other people. And besides, `age` is a nice thing to have in `user`, right?
216+
Possiamo provare a cercare tutti i posti in cui viene utilizzata nel codice e sistemarlo, ma questo potrebbe richiedere tempo e potrebbe essere ancora più complesso se lo stesso codice viene utilizzato da altre persone. E in ogni caso, `age` è una proprietà utile da avere in `user`, giusto?
217217

218-
Let's keep it.
218+
Quindi manteniamola.
219219

220-
Adding a getter for `age` solves the problem:
220+
Aggiungere un *getter* per `age` risolve il problema:
221221

222222
```js run no-beautify
223223
function User(name, birthday) {
224224
this.name = name;
225225
this.birthday = birthday;
226226

227227
*!*
228-
// age is calculated from the current date and birthday
228+
// age viene calcolata utilizzando la data attuale ed il compleanno
229229
Object.defineProperty(this, "age", {
230230
get() {
231231
let todayYear = new Date().getFullYear();
@@ -237,8 +237,8 @@ function User(name, birthday) {
237237

238238
let john = new User("John", new Date(1992, 6, 1));
239239

240-
alert( john.birthday ); // birthday is available
241-
alert( john.age ); // ...as well as the age
240+
alert( john.birthday ); // birthday è disponibile
241+
alert( john.age ); // ...è lo è anche age
242242
```
243243

244-
Now the old code works too and we've got a nice additional property.
244+
In questo modo il codice "vecchio" continua a funzionare e abbiamo anche guadagnato un'ottima proprietà aggiuntiva.

0 commit comments

Comments
 (0)