Skip to content

Commit f0c2eee

Browse files
authored
Merge pull request #231 from longo-andrea/article/static-properties
Static properties and methods
2 parents d6a8ccf + 3920a19 commit f0c2eee

File tree

3 files changed

+70
-70
lines changed

3 files changed

+70
-70
lines changed
Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
First, let's see why the latter code doesn't work.
1+
Come prima cosa, cerchiamo di capire perché il codice non funziona.
22

3-
The reason becomes obvious if we try to run it. An inheriting class constructor must call `super()`. Otherwise `"this"` won't be "defined".
3+
La motivazione appare piuttosto ovvia se proviamo ad eseguire il codice. Un classe che eredita, deve invocare `super()`. Diversamente, il valore di `"this"` non sarà "definito".
44

5-
So here's the fix:
5+
Vediamo come sistemarlo:
66

77
```js run
88
class Rabbit extends Object {
99
constructor(name) {
1010
*!*
11-
super(); // need to call the parent constructor when inheriting
11+
super(); // dobbiamo chiamare il costruttore padre della classe da cui stiamo ereditando
1212
*/!*
1313
this.name = name;
1414
}
@@ -19,16 +19,16 @@ let rabbit = new Rabbit("Rab");
1919
alert( rabbit.hasOwnProperty('name') ); // true
2020
```
2121

22-
But that's not all yet.
22+
Ma non è tutto.
2323

24-
Even after the fix, there's still important difference in `"class Rabbit extends Object"` versus `class Rabbit`.
24+
Anche dopo questo fix, c'è ancora un grande differenza tra `"class Rabbit extends Object"` e `class Rabbit`.
2525

26-
As we know, the "extends" syntax sets up two prototypes:
26+
Come già sappiamo, la sintassi "extends" imposta due prototype:
2727

28-
1. Between `"prototype"` of the constructor functions (for methods).
29-
2. Between the constructor functions themselves (for static methods).
28+
1. Tra `"prototype"` del costruttore (per i metodi).
29+
2. Tra i costruttori stessi (per i metodi statici).
3030

31-
In our case, for `class Rabbit extends Object` it means:
31+
Nel nostro caso, `class Rabbit extends Object` significa:
3232

3333
```js run
3434
class Rabbit extends Object {}
@@ -37,45 +37,45 @@ alert( Rabbit.prototype.__proto__ === Object.prototype ); // (1) true
3737
alert( Rabbit.__proto__ === Object ); // (2) true
3838
```
3939

40-
So `Rabbit` now provides access to static methods of `Object` via `Rabbit`, like this:
40+
In questo modo, tramite `Rabbit` abbiamo accesso ai metodi statici di `Object`, come nell'esempio:
4141

4242
```js run
4343
class Rabbit extends Object {}
4444

4545
*!*
46-
// normally we call Object.getOwnPropertyNames
46+
// normalmente invochiamo Object.getOwnPropertyNames
4747
alert ( Rabbit.getOwnPropertyNames({a: 1, b: 2})); // a,b
4848
*/!*
4949
```
5050

51-
But if we don't have `extends Object`, then `Rabbit.__proto__` is not set to `Object`.
51+
Ma se non estendiamo l'oggetto, con`extends Object`, allora `Rabbit.__proto__` non sarà impostato a `Object`.
5252

53-
Here's the demo:
53+
Qui una demo:
5454

5555
```js run
5656
class Rabbit {}
5757

5858
alert( Rabbit.prototype.__proto__ === Object.prototype ); // (1) true
5959
alert( Rabbit.__proto__ === Object ); // (2) false (!)
60-
alert( Rabbit.__proto__ === Function.prototype ); // as any function by default
60+
alert( Rabbit.__proto__ === Function.prototype ); // come qualsiasi funzione di default
6161

6262
*!*
63-
// error, no such function in Rabbit
63+
// errore, funzione non esistente in Rabbit
6464
alert ( Rabbit.getOwnPropertyNames({a: 1, b: 2})); // Error
6565
*/!*
6666
```
6767

68-
So `Rabbit` doesn't provide access to static methods of `Object` in that case.
68+
Quindi `Rabbit`, in questo caso, non fornisce l'accesso ai metodi statici di `Object`.
6969

70-
By the way, `Function.prototype` has "generic" function methods, like `call`, `bind` etc. They are ultimately available in both cases, because for the built-in `Object` constructor, `Object.__proto__ === Function.prototype`.
70+
In ogni caso, `Function.prototype` possiede metodi "generici", come `call`, `bind` etc. Questi saranno disponibili in entrambi i casi, grazie al costruttore di `Object`, `Object.__proto__ === Function.prototype`.
7171

72-
Here's the picture:
72+
Come mostrato in figura:
7373

7474
![](rabbit-extends-object.svg)
7575

76-
So, to put it short, there are two differences:
76+
Quindi, per riassumere, ci sono due principali differenze:
7777

7878
| class Rabbit | class Rabbit extends Object |
7979
|--------------|------------------------------|
80-
| -- | needs to call `super()` in constructor |
80+
| -- | dobbiamo invocare `super()` nel costruttore |
8181
| `Rabbit.__proto__ === Function.prototype` | `Rabbit.__proto__ === Object` |

1-js/09-classes/03-static-properties-methods/3-class-extend-object/task.md

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@ importance: 3
44

55
# Class extends Object?
66

7-
As we know, all objects normally inherit from `Object.prototype` and get access to "generic" object methods like `hasOwnProperty` etc.
7+
Come ormai sappiamo, tutti gli oggetti, normalmente ereditano da `Object.prototype` ed hanno accesso ai metodi generici di `Object`, come `hasOwnProperty` etc.
88

9-
For instance:
9+
Ad esempio:
1010

1111
```js run
1212
class Rabbit {
@@ -18,16 +18,16 @@ class Rabbit {
1818
let rabbit = new Rabbit("Rab");
1919

2020
*!*
21-
// hasOwnProperty method is from Object.prototype
21+
// hasOwnProperty viene ereditato da Object.prototype
2222
alert( rabbit.hasOwnProperty('name') ); // true
2323
*/!*
2424
```
2525

26-
But if we spell it out explicitly like `"class Rabbit extends Object"`, then the result would be different from a simple `"class Rabbit"`?
26+
Ma se lo invocassimo esplicitamente in questo modo: `"class Rabbit extends Object"`, allora il risultato sarebbe diverso da un semplice `"class Rabbit"`?
2727

28-
What's the difference?
28+
Qual'è la differenza?
2929

30-
Here's an example of such code (it doesn't work -- why? fix it?):
30+
Qui vediamo un esempio (perché non funziona? è possibile sistemarlo?):
3131

3232
```js
3333
class Rabbit extends Object {

1-js/09-classes/03-static-properties-methods/article.md

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

2-
# Static properties and methods
2+
# Proprietà e metodi statici
33

4-
We can also assign a method to the class function itself, not to its `"prototype"`. Such methods are called *static*.
4+
Possiamo anche assegnare metodi alle classi stesse, non solamente al loro `"prototype"`. Questi metodi sono detti *statici*.
55

6-
In a class, they are prepended by `static` keyword, like this:
6+
All'interno della classe, questi vengono preceduti dalla keyword `static`, come possiamo vedere nell'esempio:
77

88
```js run
99
class User {
@@ -17,7 +17,7 @@ class User {
1717
User.staticMethod(); // true
1818
```
1919

20-
That actually does the same as assigning it as a property directly:
20+
Questo avrà lo stesso effetto di assegnarla direttamente come proprietà:
2121

2222
```js run
2323
class User { }
@@ -29,11 +29,11 @@ User.staticMethod = function() {
2929
User.staticMethod(); // true
3030
```
3131

32-
The value of `this` in `User.staticMethod()` call is the class constructor `User` itself (the "object before dot" rule).
32+
Il valore di `this` nella chiamata `User.staticMethod()` è rappresentato dal costruttore dell classe `User` (la regola dell' "oggetto prima del punto").
3333

34-
Usually, static methods are used to implement functions that belong to the class, but not to any particular object of it.
34+
Solitamente, i metodi statici vengono utilizzati per rappresentare funzioni che appartengono alla classe, ma non ad un oggetto in particolare.
3535

36-
For instance, we have `Article` objects and need a function to compare them. A natural solution would be to add `Article.compare` method, like this:
36+
Ad esempio, potremmo avere degli oggetti di tipo `Article` e necessitare di una funzione per confrontarli. Una soluzione naturale sarebbe quella di aggiungere il metodo `Article.compare`, come nell'esempio:
3737

3838
```js run
3939
class Article {
@@ -63,17 +63,17 @@ articles.sort(Article.compare);
6363
alert( articles[0].title ); // CSS
6464
```
6565

66-
Here `Article.compare` stands "above" articles, as a means to compare them. It's not a method of an article, but rather of the whole class.
66+
Qui `Article.compare` sta "al di sopra" degli articoli, poiché ha lo scopo di confrontarli. Non è un metodo di un articolo, ma piuttosto dell'intera classe.
6767

68-
Another example would be a so-called "factory" method. Imagine, we need few ways to create an article:
68+
Un altro esempio comune è quello del "factory method" (un particolare design pattern). Immaginiamo di avere bisogno di diverse modalità di creazione di un articolo:
6969

70-
1. Create by given parameters (`title`, `date` etc).
71-
2. Create an empty article with today's date.
72-
3. ...or else somehow.
70+
1. Creazione con i parametri forniti (`title`, `date` etc).
71+
2. Creazione di un articolo vuoto con la data di oggi.
72+
3. ...o qualsiasi altra modalità.
7373

74-
The first way can be implemented by the constructor. And for the second one we can make a static method of the class.
74+
Il primo metodo può essere implementato tramite il costruttore. Mentre per il secondo, possiamo creare un metodo statico appartenente alla classe.
7575

76-
Like `Article.createTodays()` here:
76+
Come `Article.createTodays()` nell'esempio:
7777

7878
```js run
7979
class Article {
@@ -84,7 +84,7 @@ class Article {
8484

8585
*!*
8686
static createTodays() {
87-
// remember, this = Article
87+
// ricorda, this = Article
8888
return new this("Today's digest", new Date());
8989
}
9090
*/!*
@@ -95,21 +95,21 @@ let article = Article.createTodays();
9595
alert( article.title ); // Today's digest
9696
```
9797

98-
Now every time we need to create a today's digest, we can call `Article.createTodays()`. Once again, that's not a method of an article, but a method of the whole class.
98+
Ora, ogni volta in cui avremo bisogno di crare un "today's digest", possiamo invocare `Article.createTodays()`. Ripetiamolo nuovamente, questo non è un metodo per uno specifico articolo, ma piuttosto un metodo dell'intera classe.
9999

100-
Static methods are also used in database-related classes to search/save/remove entries from the database, like this:
100+
I metodi statici vengono utilizzati anche nelle classi database-related (relative a database), per poter cercare/salvare/rimuovere elementi dal database, come nell'esempio:
101101

102102
```js
103-
// assuming Article is a special class for managing articles
104-
// static method to remove the article:
103+
// assumiamo che Article sia una classe speciale per la gestione degli articoli
104+
// metodo statico per la rimozione di un articolo:
105105
Article.remove({id: 12345});
106106
```
107107

108-
## Static properties
108+
## Proprietà statiche
109109

110110
[recent browser=Chrome]
111111

112-
Static properties are also possible, they look like regular class properties, but prepended by `static`:
112+
E' anche possibile definire proprietà statiche, queste sono molto simili alle proprietà della classe, ma sono precedute dalla keyword `static`:
113113

114114
```js run
115115
class Article {
@@ -119,17 +119,17 @@ class Article {
119119
alert( Article.publisher ); // Ilya Kantor
120120
```
121121

122-
That is the same as a direct assignment to `Article`:
122+
Lo stesso che si otterrebbe con un assegnazione diretta ad `Article`:
123123

124124
```js
125125
Article.publisher = "Ilya Kantor";
126126
```
127127

128-
## Inheritance of static properties and methods
128+
## Ereditarietà delle proprietà e dei metodi statici
129129

130-
Static properties and methods are inherited.
130+
Anche le proprietà ed i metodi statici vengono ereditati.
131131

132-
For instance, `Animal.compare` and `Animal.planet` in the code below are inherited and accessible as `Rabbit.compare` and `Rabbit.planet`:
132+
Ad esempio, `Animal.compare` e `Animal.planet` nel codice sotto, vengono ereditate e diventano quindi accessibili come `Rabbit.compare` e `Rabbit.planet`:
133133

134134
```js run
135135
class Animal {
@@ -153,7 +153,7 @@ class Animal {
153153

154154
}
155155

156-
// Inherit from Animal
156+
// Eredita da Animal
157157
class Rabbit extends Animal {
158158
hide() {
159159
alert(`${this.name} hides!`);
@@ -174,43 +174,43 @@ rabbits[0].run(); // Black Rabbit runs with speed 5.
174174
alert(Rabbit.planet); // Earth
175175
```
176176

177-
Now when we call `Rabbit.compare`, the inherited `Animal.compare` will be called.
177+
Ora, quando invochiamo `Rabbit.compare`, verrà invocato il metodo `Animal.compare` ereditato.
178178

179-
How does it work? Again, using prototypes. As you might have already guessed, `extends` gives `Rabbit` the `[[Prototype]]` reference to `Animal`.
179+
Come funziona? Nuovamente, utilizzando il prototypes. Come potrete aver già intuito, `extends` fornisce a `Rabbit` il riferimento a `[[Prototype]]` di `Animal`.
180180

181181
![](animal-rabbit-static.svg)
182182

183183
![](animal-rabbit-static.svg)
184184

185-
1. `Rabbit` function prototypally inherits from `Animal` function.
186-
2. `Rabbit.prototype` prototypally inherits from `Animal.prototype`.
185+
1. La funzione `Rabbit` eredita dalla funzione di `Animal` .
186+
2. `Rabbit.prototype` eredita il prototye di `Animal.prototype`.
187187

188-
As a result, inheritance works both for regular and static methods.
188+
Come risultato, l'ereditarietà funziona sia per i metodi regolari che per quelli statici.
189189

190-
Here, let's check that by code:
190+
Ora, verifichiamo quanto detto guardando al codice:
191191

192192
```js run
193193
class Animal {}
194194
class Rabbit extends Animal {}
195195

196-
// for statics
196+
// per proprietà statiche
197197
alert(Rabbit.__proto__ === Animal); // true
198198

199-
// for regular methods
199+
// per proprietà regolari
200200
alert(Rabbit.prototype.__proto__ === Animal.prototype); // true
201201
```
202202

203-
## Summary
203+
## Riepilogo
204204

205-
Static methods are used for the functionality that belongs to the class "as a whole". It doesn't relate to a concrete class instance.
205+
I metodi statici vengono utilizzati per funzionalità che appartengono all'intera classe. Non hanno nulla a che fare con l'istanza della classe.
206206

207-
For example, a method for comparison `Article.compare(article1, article2)` or a factory method `Article.createTodays()`.
207+
Ad esempio, un metodo per il confronto `Article.compare(article1, article2)` o un factory method `Article.createTodays()`.
208208

209-
They are labeled by the word `static` in class declaration.
209+
Queste vengono precedute dalla keyword `static` all'interno della dichiarazione della classe.
210210

211-
Static properties are used when we'd like to store class-level data, also not bound to an instance.
211+
Le proprietà statiche vengono utilizzate quando si ha intenzione di memorizzare dati relativi alla classe, che non sono quindi legati ad un'istanza precisa.
212212

213-
The syntax is:
213+
La sintassi è:
214214

215215
```js
216216
class MyClass {
@@ -222,13 +222,13 @@ class MyClass {
222222
}
223223
```
224224

225-
Technically, static declaration is the same as assigning to the class itself:
225+
Tecnicamente, le dichiarazioni di proprietà statiche equivalgono all'assegnazione diretta alla classe stessa:
226226

227227
```js
228228
MyClass.property = ...
229229
MyClass.method = ...
230230
```
231231

232-
Static properties and methods are inherited.
232+
Le proprietà ed i metodi statici vengono ereditati.
233233

234-
For `class B extends A` the prototype of the class `B` itself points to `A`: `B.[[Prototype]] = A`. So if a field is not found in `B`, the search continues in `A`.
234+
Nel caso in cui `class B extends A` il prototype della classe `B` punta ad `A`: `B.[[Prototype]] = A`. Quindi se un campo non viene trovato in `B`, la ricerca continuerà in `A`.

0 commit comments

Comments
 (0)