1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
|
---
title: Introduzione a JavaScript Object-Oriented
slug: Web/JavaScript/Introduzione_al_carattere_Object-Oriented_di_JavaScript
tags:
- Classe
- Costruttore
- Eredità
- Incapsulamento
- Membri
- Oggetto
- Orientato agli oggetti
translation_of: Learn/JavaScript/Objects
translation_of_original: Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
---
<p>{{jsSidebar("Introductory")}}</p>
<p>Orientato agli oggetti fino dal nucleo, JavaScript offre funzionalità {{Glossary("OOP")}} potenti e flessibili. <span id="result_box" lang="it"><span class="hps">Questo</span> <span class="hps">articolo inizia</span> <span class="hps">con una introduzione</span> <span class="hps">alla</span> <span class="hps">programmazione</span> <span class="hps">orientata agli oggetti</span><span>,</span> quindi presenta <span class="hps">il</span> <span class="hps">modello di oggetti</span> <span class="hps">JavaScript</span> <span class="hps">e, infine,</span> <span class="hps">dimostra</span> <span class="hps">concetti della</span> <span class="hps">programmazione orientata agli oggetti</span> <span class="hps">in JavaScript</span><span>.</span></span></p>
<h2 id="JavaScript_Review" name="JavaScript_Review">Riesame su JavaScript</h2>
<p><span id="result_box" lang="it"><span class="hps">Se</span> <span class="hps">non ti senti</span> <span class="hps">sicuro su</span> <span class="hps">concetti</span> <span class="hps">JavaScript</span><span> come</span> <span class="hps">variabili, tipi</span><span>, funzioni e</span> <span class="hps">ambito di applicazione</span><span>,</span> <span class="hps">puoi leggere su</span> <span class="hps">questi argomenti</span> </span>in <a href="/it/JavaScript/Una_re-introduzione_a_JavaScript" title="it/JavaScript/Una_re-introduzione_a_JavaScript">A re-introduction to JavaScript</a>. Puoi<span lang="it"><span class="hps"> inoltre consultare</span> <span class="hps">la</span></span> <a href="/it/JavaScript/Guida" title="it/JavaScript/Guida">Core JavaScript 1.5 Guide</a>.</p>
<h2 id="Object-oriented_programming" name="Object-oriented_programming">Programmazione object-oriented</h2>
<p>La programmazione orientata agli oggetti è un paradigma di programmazione che usa astrazione ({{glossary("abstraction")}}) per creare modelli basati sul mondo reale. Utilizza diverse tecniche di paradigmi esistenti, tra cui la modularità ({{glossary("modularity")}}), il polimorfismo ({{glossary("polymorphism")}}) e l'incapsulamento ({{glossary("encapsulation")}}). Oggi molti linguaggi di programmazione (come Java, JavaScript, C #, C ++, Python, PHP, Ruby e Objective-C) supportano la programmazione orientata agli oggetti (OOP).</p>
<p><span id="result_box" lang="it">OOP <span class="hps">ha una visione del</span> <span class="hps">software come</span> <span class="hps">un insieme di oggetti</span> <span class="hps">cooperanti</span><span>,</span> <span class="hps">piuttosto che </span><span class="hps">un insieme di funzioni</span> <span class="hps">o semplicemente </span><span class="hps">un elenco</span> <span class="hps">di istruzioni per il</span> <span class="hps">computer (come è nella visione tradizionale).</span> <span class="hps">In</span> <span class="hps">OOP</span><span>,</span> <span class="hps">ogni oggetto è</span> <span class="hps">in grado di ricevere</span> <span class="hps">messaggi</span><span>,</span> <span class="hps">elaborare dati</span><span>,</span> <span class="hps">e</span> <span class="hps">inviare messaggi</span> <span class="hps">ad altri oggetti</span><span>.</span> <span class="hps">Ogni oggetto</span> <span class="hps">può essere visto come</span> <span class="hps">una</span> <span class="hps">piccola macchina</span> <span class="hps">indipendente con</span> </span><span lang="it"><span class="hps">ruolo o</span> <span class="hps">responsabilità</span><span> distinti.</span></span></p>
<p><span id="result_box" lang="it"><span class="hps">OOP</span> <span class="hps">promuove una maggiore</span> <span class="hps">flessibilità e</span> mantenibilità <span class="hps">nella</span> <span class="hps">programmazione</span><span>,</span> <span class="hps">ed è</span> <span class="hps">molto popolare</span> <span class="hps">in</span> <span class="hps">ingegneria del software su larga scala</span><span>.</span> <span class="hps">Poiché</span> <span class="hps">OOP</span> <span class="hps">sottolinea con forza</span> <span class="hps">la modularità</span><span>,</span> <span class="hps">il codice</span> <span class="hps">object-oriented</span> <span class="hps">è più semplice da</span> <span class="hps">sviluppare e</span> <span class="hps">più facile da capire</span> <span class="hps">in seguito.</span> <span class="hps">Il codice</span> <span class="hps">object-oriented</span> <span class="hps">promuove</span> <span class="hps">un'analisi</span><span>,</span> <span class="hps">codifica</span><span>,</span> <span class="hps">e comprensione</span> <span class="hps">di</span> <span class="hps">situazioni</span></span><span lang="it"><span class="hps"> e</span> <span class="hps">procedure</span></span><span id="result_box" lang="it"><span class="hps"> complesse</span></span><span lang="it"><span class="hps"> più</span> <span class="hps">diretta</span> <span class="hps">che con</span> <span class="hps">metodi di programmazione</span> <span class="hps">a minor modularità</span></span><sup>.</sup><a href="https://developer.mozilla.org/it/docs/Web/JavaScript/Introduzione_al_carattere_Object-Oriented_di_JavaScript$edit#cite-1"><sup>1</sup></a></p>
<h2 id="Terminology" name="Terminology">Terminologia</h2>
<dl>
<dt>{{Glossary("Namespace")}}</dt>
<dd><span id="result_box" lang="it"><span class="hps">Un contenitore</span> <span class="hps">che</span> <span class="hps">consente agli sviluppatori di</span> <span class="hps">includere tutte</span> <span class="hps">le funzionalità</span> <span class="hps">sotto</span> <span class="hps">un</span> <span class="hps">nome unico, specifico per l'</span><span class="hps">applicazione</span><span>.</span></span></dd>
<dt>{{Glossary("Class")}}</dt>
<dd><span id="result_box" lang="it"><span class="hps">Definisce</span> <span class="hps">le caratteristiche dell'oggetto</span><span>.</span> <span class="hps">Una classe</span> <span class="hps">è una definizione</span> <span class="hps">del modello,</span> <span class="hps">delle proprietà e dei metodi</span> <span class="hps">di un oggetto</span><span>.</span></span></dd>
<dt>{{Glossary("Object")}}</dt>
<dd>Istanza di una classe.</dd>
<dt>{{Glossary("Property")}}</dt>
<dd>Una caratteristica di un oggetto, come un colore.</dd>
<dt>{{Glossary("Method")}}</dt>
<dd>Una capacità di un oggetto, come ad esempio cammina. È una procedura o funzione associata a una classe.</dd>
<dt>{{Glossary("Constructor")}}</dt>
<dd>Un metodo invocato nel momento in cui l'oggetto viene istanziato. Di solito ha lo stesso nome della classe che lo contiene.</dd>
<dt>{{Glossary("Inheritance")}}</dt>
<dd>Una classe può ereditare caratteristiche da un'altra classe.</dd>
<dt>{{Glossary("Encapsulation")}}</dt>
<dd>Una modalità di raggruppamento di dati e metodi che ne fanno uso.</dd>
<dt>{{Glossary("Abstraction")}}</dt>
<dd>L'insieme del complesso di eredità, metodi e proprietà di un oggetto deve rispecchiare adeguatamente un modello reale.</dd>
<dt>{{Glossary("Polymorphism")}}</dt>
<dd><span id="result_box" lang="it"><span class="hps">Poly </span><span class="hps">significa</span> <span class="hps">"<em>molti</em>"</span> <span class="hps">e</span> <span class="hps">morfismo</span> <span class="hps">significa</span> <span class="hps">"<em>forme</em>"</span><span>.</span> <span class="hps">Classi diverse </span><span class="hps">potrebbero</span> <span class="hps">definire lo stesso</span> <span class="hps">metodo o proprietà</span><span>.</span></span></dd>
</dl>
<p><span id="result_box" lang="it"><span class="hps">Per una</span> <span class="hps">descrizione</span> </span><span lang="it"><span class="hps">più ampia</span> <span class="hps">della programmazione</span> <span class="hps">orientata agli oggetti</span><span>, vedi</span> </span>{{interwiki("wikipedia", "Object-oriented programming")}}<span lang="it"> <span class="hps">su Wikipedia</span><span>.</span></span></p>
<h2 id="Programmazione_prototype-based">Programmazione prototype-based</h2>
<p><span id="result_box" lang="it"><span class="hps">La programmazione p</span></span>rototype-based<span lang="it"><span class="hps"> (basata</span> <span class="hps">sul prototipo)</span> <span class="hps">è un modello</span> <span class="hps">OOP</span> <span class="hps">che non utilizza</span> <span class="hps">le classi</span><span>,</span> <span class="hps">ma piuttosto</span> <span class="hps">prima</span> <span class="hps">completa</span> <span class="hps">il comportamento di</span> <span class="hps">qualsiasi classe</span> <span class="hps">e</span> <span class="hps">poi</span> <span class="hps">riutilizza</span> <span class="atn hps">(</span><span>equivalente</span> <span class="hps">all'</span><span class="hps">ereditarietà</span> <span class="hps">nei linguaggi</span> <span class="hps">basati su classi</span><span>)</span> arricchendo <span class="atn hps">(</span><span>o sviluppando</span><span>)</span> <span class="hps">oggetti <em>prototipo</em></span><span class="hps"> esistenti</span><span>.</span> <span class="atn hps">(</span><span>Chiamata anche</span> <span class="hps">senza classi (</span></span>classless<span lang="it"><span class="hps">)</span><span>,</span> <span class="hps">orientata al prototipo</span><span> (</span></span>prototype-oriented<span lang="it"><span>),</span> <span class="hps">o</span> <span class="hps">programmazione basata</span> su <span class="hps">istanza</span><span> (</span></span>instance-based<span lang="it"><span>).</span><span>)</span></span></p>
<p><span id="result_box" lang="it"><span class="hps">L'esempio </span></span><span lang="it"><span class="hps">originale</span> <span class="atn hps">(</span><span>e più</span> <span class="hps">canonico</span><span>)</span> <span class="hps"> di un</span> <span class="hps">linguaggio basato sui prototipi</span> <span class="hps">è</span> </span>{{interwiki("wikipedia", "Self (programming language)", "Self")}}<span lang="it"> <span class="hps">sviluppato da</span> <span class="hps">David</span> <span class="hps">Ungar</span> <span class="hps">e Randall</span> <span class="hps">Smith</span><span>.</span> <span class="hps">Tuttavia lo</span> <span class="hps">stile di programmazione</span> <span class="atn hps">senza classi diventa</span> <span class="hps">sempre più popolare</span> <span class="hps">negli ultimi tempi,</span> <span class="hps">ed è stato adottato</span> <span class="hps">per</span> <span class="hps">i linguaggi di programmazione</span> <span class="hps">come JavaScript</span><span>,</span> <span class="hps">Cecil</span><span>,</span> <span class="hps">NewtonScript</span><span>,</span> <span class="hps">Io,</span> <span class="hps">MOO</span><span>,</span> <span class="hps">REBOL</span><span>,</span> <span class="hps">Kevo</span><span>,</span> <span class="hps">Squeak</span> <span class="atn hps">(</span><span>quando si utilizza il</span> <span class="hps">framework</span> </span>Viewer per<span lang="it"><span class="hps"> manipolare</span> <span class="hps">componenti</span> <span class="hps">Morphic</span><span>)</span><span>,</span> <span class="hps">e</span> <span class="hps">molti altri</span></span>.<a href="https://developer.mozilla.org/it/docs/Web/JavaScript/Introduzione_al_carattere_Object-Oriented_di_JavaScript$edit#cite-1"><sup>1</sup></a></p>
<h2 id="JavaScript_Object_Oriented_Programming" name="JavaScript_Object_Oriented_Programming">Programmazione Object Oriented in JavaScript</h2>
<h3 id="Namespace">Namespace</h3>
<p>Un namespace <span id="result_box" lang="it"><span class="hps">è un contenitore</span> <span class="hps">che</span> <span class="hps">consente agli sviluppatori di</span> <span class="hps">includere tutte</span> <span class="hps">le funzionalità</span> <span class="hps">sotto</span> <span class="hps">un</span> <span class="hps">nome unico, specifico per l'</span><span class="hps">applicazione</span></span>. <strong>In JavaScript un namespace è solo un altro oggetto che contiene metodi, proprietà e oggetti.</strong></p>
<div class="note">
<p><strong>Nota:</strong> È <span lang="it"><span>importante notare che</span> <span class="hps">in JavaScript</span> <span class="hps">non c'è alcuna differenza</span> <span class="hps">a livello di</span> <span class="hps">linguaggio</span> <span class="hps">tra oggetti</span> <span class="hps">regolari e </span>namespace<span>.</span> <span class="hps">Questo</span> <span class="hps">differenzia da molti altri</span> <span class="hps">linguaggi orientati agli oggetti</span> <span class="hps">e può essere fonte</span><span class="hps"> di confusione</span> <span class="hps">per i nuovi</span> <span class="hps">programmatori JavaScript</span></span>.</p>
</div>
<p><span id="result_box" lang="it"><span class="hps">L'idea alla base</span> del<span class="hps">la creazione di</span> <span class="hps">un namespace</span> <span class="hps">in JavaScript</span> <span class="hps">è</span> <span class="hps">semplice: creare</span> <span class="hps">un oggetto</span> <span class="hps">globale</span><span>,</span> <span class="hps">e</span> <span class="hps">tutte le variabili</span><span>,</span> <span class="hps">i metodi</span> <span class="hps">e le funzioni</span> <span class="hps">diventano</span> <span class="hps">proprietà di tale oggetto</span><span>.</span> <span class="hps">L'uso</span> <span class="hps">dei namespace</span> <span class="hps">riduce anche</span> <span class="hps">il rischio di</span> <span class="hps">conflitti tra nomi</span> <span class="hps">in un'applicazione</span><span>,</span> <span class="hps">poiché gli oggetti</span> <span class="hps">di ciascuna applicazione</span> <span class="hps">sono</span> <span class="hps">proprietà di un</span> <span class="hps">oggetto globale</span> <span class="hps">definito dall'applicazione</span><span>.</span></span></p>
<p>Creiamo un oggetto globale chiamato MYAPP:</p>
<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// global namespace</span>
<span class="keyword token">var</span> MYAPP <span class="operator token">=</span> MYAPP <span class="operator token">||</span> <span class="punctuation token">{</span><span class="punctuation token">}</span><span class="punctuation token">;</span></code></pre>
<p><span id="result_box" lang="it"><span class="hps">Nel</span> <span class="hps">codice di esempio di</span> <span class="hps">sopra</span> prima viene testato <span class="hps">se</span> <span class="hps">MYAPP</span> <span class="hps">è già definito</span> <span class="hps">(sia nello</span> <span class="hps">stesso o</span> <span class="hps">in un altro file</span><span>)</span><span>.</span> <span class="hps">Se sì, allora</span> <span class="atn hps">viene utilizzato l'</span><span class="hps">oggetto globale </span></span><span lang="it"><span>MYAPP già</span> <span class="hps">esistente</span><span>,</span> <span class="hps">altrimenti</span> viene creato<span class="hps"> un oggetto</span> <span class="hps">vuoto chiamato</span> <span class="hps">MYAPP</span> <span class="hps">che</span> <span class="hps">incapsula</span> <span class="hps">metodi,</span> <span class="hps">funzioni, variabili</span> <span class="hps">e oggetti</span><span>.</span></span></p>
<p>Possaimo anche creare sotto-namespace (tieni presente che l'oggetto globale deve essere definito prima):</p>
<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// sub namespace</span>
MYAPP<span class="punctuation token">.</span>event <span class="operator token">=</span> <span class="punctuation token">{</span><span class="punctuation token">}</span><span class="punctuation token">;</span></code></pre>
<p><span id="result_box" lang="it"><span class="hps">La seguente</span> <span class="hps">è</span> <span class="hps">la sintassi del codice</span> <span class="hps">per</span> <span class="hps">la creazione di un</span> namespace <span class="hps">e l'aggiunta di</span> <span class="hps">variabili, funzioni</span><span>,</span> <span class="hps">e</span> <span class="hps">un metodo:</span></span></p>
<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// Create container called MYAPP.commonMethod for common method and properties</span>
MYAPP<span class="punctuation token">.</span>commonMethod <span class="operator token">=</span> <span class="punctuation token">{</span>
regExForName<span class="punctuation token">:</span> <span class="string token">""</span><span class="punctuation token">,</span> <span class="comment token">// define regex for name validation</span>
regExForPhone<span class="punctuation token">:</span> <span class="string token">""</span><span class="punctuation token">,</span> <span class="comment token">// define regex for phone no validation</span>
validateName<span class="punctuation token">:</span> <span class="keyword token">function</span><span class="punctuation token">(</span>name<span class="punctuation token">)</span><span class="punctuation token">{</span>
<span class="comment token">// Do something with name, you can access regExForName variable</span>
<span class="comment token">// using "this.regExForName"</span>
<span class="punctuation token">}</span><span class="punctuation token">,</span>
validatePhoneNo<span class="punctuation token">:</span> <span class="keyword token">function</span><span class="punctuation token">(</span>phoneNo<span class="punctuation token">)</span><span class="punctuation token">{</span>
<span class="comment token">// do something with phone number</span>
<span class="punctuation token">}</span>
<span class="punctuation token">}</span>
<span class="comment token">// Object together with the method declarations</span>
MYAPP<span class="punctuation token">.</span>event <span class="operator token">=</span> <span class="punctuation token">{</span>
addListener<span class="punctuation token">:</span> <span class="keyword token">function</span><span class="punctuation token">(</span>el<span class="punctuation token">,</span> type<span class="punctuation token">,</span> fn<span class="punctuation token">)</span> <span class="punctuation token">{</span>
<span class="comment token">// code stuff</span>
<span class="punctuation token">}</span><span class="punctuation token">,</span>
removeListener<span class="punctuation token">:</span> <span class="keyword token">function</span><span class="punctuation token">(</span>el<span class="punctuation token">,</span> type<span class="punctuation token">,</span> fn<span class="punctuation token">)</span> <span class="punctuation token">{</span>
<span class="comment token">// code stuff</span>
<span class="punctuation token">}</span><span class="punctuation token">,</span>
getEvent<span class="punctuation token">:</span> <span class="keyword token">function</span><span class="punctuation token">(</span>e<span class="punctuation token">)</span> <span class="punctuation token">{</span>
<span class="comment token">// code stuff</span>
<span class="punctuation token">}</span>
<span class="comment token">// Can add another method and properties</span>
<span class="punctuation token">}</span>
<span class="comment token">// Syntax for Using addListener method:</span>
MYAPP<span class="punctuation token">.</span>event<span class="punctuation token">.</span><span class="function token">addListener</span><span class="punctuation token">(</span><span class="string token">"yourel"</span><span class="punctuation token">,</span> <span class="string token">"type"</span><span class="punctuation token">,</span> callback<span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre>
<h3 id="Oggetti_incorporati_built-in_standard">Oggetti incorporati (built-in) standard</h3>
<p><span id="result_box" lang="it"><span class="hps">JavaScript</span> <span class="hps">ha diversi</span> <span class="hps">oggetti inclusi</span> <span class="hps">nel suo nucleo</span><span>,</span> <span class="hps">per esempio ci</span> <span class="hps">sono</span> <span class="hps">oggetti come</span> </span>Math, Object, Array e String<span lang="it"><span>.</span> <span class="hps">L'esempio seguente mostra</span> <span class="hps">come utilizzare</span> <span class="hps">l'oggetto</span> <span class="hps">Math per</span> <span class="hps">ottenere</span> <span class="hps">un numero casuale</span> <span class="hps">utilizzando</span> <span class="hps">il suo</span> <span class="hps">metodo</span></span> <code>random()</code> <span lang="it"><span>.</span></span></p>
<pre class="brush: js line-numbers language-js"><code class="language-js">console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>Math<span class="punctuation token">.</span><span class="function token">random</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre>
<div class="note"><strong>Nota:</strong> <span id="result_box" lang="it"><span class="hps">Questo</span> <span class="hps">e</span> <span class="hps">tutti gli</span> <span class="hps">ulteriori esempi</span> presuppongono che <span class="hps">una funzione chiamata</span></span> {{domxref("console.log()")}} <span lang="it"><span class="hps">sia definita</span> <span class="hps">a livello globale</span><span>.</span> <span class="hps">La funzione</span> </span><code>console.log()</code> <span lang="it"><span class="hps">in realtà non</span> <span class="hps">è </span><span class="hps">parte</span> <span class="hps">di</span> <span class="hps">JavaScript</span> <span class="hps">in sé</span><span>,</span> <span class="hps">ma</span> <span class="hps">molti browser</span> la implementano <span class="hps">per aiutare</span> <span class="hps">il debug</span><span>.</span></span></div>
<p>Vedi <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects" title="en-US/docs/Web/JavaScript/Reference/Global_Objects">JavaScript Reference: Standard built-in objects</a> for una lista degli oggetti di nucleo in JavaScript.</p>
<p>Ogni oggetto in JavaScript è una instanza dell'oggetto <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object"><code>Object</code></a> e perciò ne eredita tutte le sue proprietà e metodi.</p>
<h3 id="Oggetti_utente">Oggetti utente</h3>
<h4 id="La_classe">La classe</h4>
<p><span id="result_box" lang="it"><span class="hps">JavaScript è un linguaggio</span> <span class="hps">basato sui prototipi</span> <span class="hps">e</span> <span class="hps">non contiene</span> <span class="hps">alcuna dichiarazione</span> <span class="hps">di classe</span><span>,</span> <span class="hps">come invece si trova</span> <span class="hps">in C</span> <span class="hps">++</span> <span class="hps">o Java</span><span>.</span> <span class="hps">Questo a volte è</span> <span class="hps">fonte di confusione per</span> <span class="hps">i programmatori</span> <span class="hps">abituati</span> <span class="hps">ai linguaggi</span> <span class="hps">con</span> <span class="hps">una dichiarazione</span></span> <code>class</code><span lang="it"><span>.</span> <span class="hps">JavaScript</span> <span class="hps">utilizza le funzioni</span> <span class="hps">come</span> <span class="hps">costruttori</span> <span class="hps">per le classi</span><span>.</span> <span class="hps">Definire una</span> <span class="hps">classe è</span> <span class="hps">facile come</span> <span class="hps">definire una funzione</span><span>.</span> <span class="hps">Nell'esempio sottostante</span> <span class="hps">si definisce una</span> <span class="hps">nuova</span> <span class="hps">classe chiamata</span> <span class="hps">Person con</span> <span class="hps">un</span> <span class="hps">costruttore vuoto</span><span>.</span></span></p>
<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">var</span> Person <span class="operator token">=</span> <span class="keyword token">function</span> <span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span><span class="punctuation token">}</span><span class="punctuation token">;</span></code></pre>
<h4 id="Loggetto_istanza_di_classe">L'oggetto (istanza di classe)</h4>
<p>Per creare una nuova istanza di un oggetto <code>obj</code> utilizziamo l'istruzione <code>new obj</code> assegnando il risultato (che è di tipo <code>obj</code>) ad una variabile, per poi accedervi successivamente.</p>
<p>Nell'esempio precedente abbiamo definito una classe chiamata <code>Person</code>. In quello seguente creiamo due istanze (<code>person1</code> e <code>person2</code>).</p>
<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">var</span> person1 <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Person</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="keyword token">var</span> person2 <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Person</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre>
<div class="note"><strong>Nota:</strong> Prego vedi {{jsxref("Object.create()")}} per un ulteriore nuovo metodo d'istanza che crea una istanza non inizializzata.</div>
<h4 id="Il_costruttore">Il costruttore</h4>
<p><span id="result_box" lang="it"><span class="hps">Il</span> <span class="hps">costruttore viene chiamato</span> quando si instanzia un oggetto <span class="atn hps">(</span><span>il momento in cui</span> <span class="hps">si crea</span> <span class="hps">l'istanza dell'oggetto</span><span>)</span><span>.</span> <span class="hps">Il</span> <span class="hps">costruttore è un</span> <span class="hps">metodo della classe</span><span>.</span> <span class="hps">In JavaScript</span> <span class="hps">la funzione</span> <span class="hps">funge da</span> <span class="hps">costruttore dell'oggetto</span><span>,</span> <span class="hps">pertanto</span> <span class="hps">non è necessario</span> <span class="hps">definire esplicitamente</span> <span class="hps">un</span> <span class="hps">metodo costruttore</span><span>.</span> <span class="hps">Ogni azione</span> <span class="hps">dichiarata</span> <span class="hps">nella classe</span> <span class="hps">viene eseguita</span> <span class="hps">al momento della</span> <span class="hps">creazione di un'istanza</span><span>.</span></span></p>
<p><span id="result_box" lang="it"><span class="hps">Il costruttore</span> <span class="hps">viene utilizzato per</span> <span class="hps">impostare le proprietà</span> <span class="hps">dell'oggetto</span> <span class="hps">o</span> <span class="hps">per chiamare</span> <span class="hps">i metodi che</span> <span class="atn hps">preparano l'</span><span>oggetto per il suo uso</span><span>.</span> <span class="hps">L'aggiunta di</span> <span class="hps">metodi di classe</span> <span class="hps">e le loro definizioni</span> <span class="hps">si effettua </span><span class="hps">utilizzando una</span> <span class="hps">sintassi diversa</span> <span class="hps">descritta più avanti in</span> <span class="hps">questo</span> <span class="hps">articolo</span><span>.</span></span></p>
<p>Nell'esempio seguente il costruttore della classe<code> Person</code> registra un messaggio quando viene istanziato un oggetto <code>Person</code>.</p>
<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">var</span> Person <span class="operator token">=</span> <span class="keyword token">function</span> <span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span>
console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">'instance created'</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="punctuation token">}</span><span class="punctuation token">;</span>
<span class="keyword token">var</span> person1 <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Person</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="keyword token">var</span> person2 <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Person</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre>
<h4 id="La_proprietà_attributo_di_oggetto">La proprietà (attributo di oggetto)</h4>
<p>Le proprietà sono variabili contenute nella classe; ogni istanza dell'oggetto ha queste proprietà. Le proprietà sono impostate nel costruttore (funzione) della classe in modo che siano creati su ogni istanza.</p>
<p><span id="result_box" lang="it"><span class="hps">La</span> <span class="hps">parola chiave</span></span> <code>this</code>, <span lang="it"><span class="hps">che si riferisce</span> <span class="hps">all'oggetto</span> <span class="hps">corrente</span><span>,</span> <span class="hps">consente di lavorare</span> <span class="hps">con le proprietà</span> <span class="hps">all'interno della classe</span><span>.</span> <span class="hps">L'accesso</span> <span class="atn hps">(</span><span>in lettura o</span> <span class="hps">scrittura)</span> <span class="hps">ad una proprietà</span> <span class="hps">al di fuori</span> <span class="hps">della classe</span> <span class="hps">è fatto con</span> <span class="hps">la sintassi</span><span>:</span> </span><code>NomeIstanza.Proprietà</code><span lang="it"><span>,</span> <span class="hps">proprio come in</span> <span class="hps">C</span> <span class="hps">++</span><span>,</span> <span class="hps">Java</span><span>,</span> <span class="hps">e molti altri linguaggi</span><span>.</span> <span class="atn hps">(</span><span>All'interno della</span> <span class="hps">classe la</span> <span class="hps">sintassi </span></span><code>this.Proprietà</code><span lang="it"><span class="hps"> è utilizzata</span> <span class="hps">per ottenere o impostare</span> <span class="hps">il valore della proprietà</span><span>.</span><span>)</span></span></p>
<p>Nell'esempio seguente, definiamo al momento della creazione la proprietà <code>firstName</code> per la classe <code>Person</code>:</p>
<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">var</span> Person <span class="operator token">=</span> <span class="keyword token">function</span> <span class="punctuation token">(</span>firstName<span class="punctuation token">)</span> <span class="punctuation token">{</span>
<span class="keyword token">this</span><span class="punctuation token">.</span>firstName <span class="operator token">=</span> firstName<span class="punctuation token">;</span>
console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">'Person instantiated'</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="punctuation token">}</span><span class="punctuation token">;</span>
<span class="keyword token">var</span> person1 <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Person</span><span class="punctuation token">(</span><span class="string token">'Alice'</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="keyword token">var</span> person2 <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Person</span><span class="punctuation token">(</span><span class="string token">'Bob'</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="comment token">// Show the firstName properties of the objects</span>
console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">'person1 is '</span> <span class="operator token">+</span> person1<span class="punctuation token">.</span>firstName<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// logs "person1 is Alice"</span>
console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">'person2 is '</span> <span class="operator token">+</span> person2<span class="punctuation token">.</span>firstName<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// logs "person2 is Bob"</span></code></pre>
<h4 id="I_metodi">I metodi</h4>
<p>I metodi sono funzioni (e definiti come funzioni), ma per il resto seguono la stessa logica delle proprietà. Chiamare un metodo è simile all'accesso a una proprietà, ma si aggiunge () alla fine del nome del metodo, eventualmente con argomenti. Per definire un metodo va assegnata una funzione a una proprietà della proprietà <code>prototype</code> della classe. In seguito sarà possibile chiamare il metodo sull'oggetto utilizzando lo stesso nome assegnato alla funzione.</p>
<p>Nell'esempio seguente definiamo e usiamo il metodo <code>sayHello()</code> per la classe <code>Person</code>.</p>
<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">var</span> Person <span class="operator token">=</span> <span class="keyword token">function</span> <span class="punctuation token">(</span>firstName<span class="punctuation token">)</span> <span class="punctuation token">{</span>
<span class="keyword token">this</span><span class="punctuation token">.</span>firstName <span class="operator token">=</span> firstName<span class="punctuation token">;</span>
<span class="punctuation token">}</span><span class="punctuation token">;</span>
Person<span class="punctuation token">.</span>prototype<span class="punctuation token">.</span>sayHello <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span>
console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">"Hello, I'm "</span> <span class="operator token">+</span> <span class="keyword token">this</span><span class="punctuation token">.</span>firstName<span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="punctuation token">}</span><span class="punctuation token">;</span>
<span class="keyword token">var</span> person1 <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Person</span><span class="punctuation token">(</span><span class="string token">"Alice"</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="keyword token">var</span> person2 <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Person</span><span class="punctuation token">(</span><span class="string token">"Bob"</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="comment token">// call the Person sayHello method.</span>
person1<span class="punctuation token">.</span><span class="function token">sayHello</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// logs "Hello, I'm Alice"</span>
person2<span class="punctuation token">.</span><span class="function token">sayHello</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// logs "Hello, I'm Bob"</span></code></pre>
<p>In JavaScript i metodi sono oggetti funzione regolarmente associati a un oggetto come una proprietà, il che significa che è possibile richiamare i metodi "fuori dal contesto". Si consideri il seguente codice di esempio:</p>
<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">var</span> Person <span class="operator token">=</span> <span class="keyword token">function</span> <span class="punctuation token">(</span>firstName<span class="punctuation token">)</span> <span class="punctuation token">{</span>
<span class="keyword token">this</span><span class="punctuation token">.</span>firstName <span class="operator token">=</span> firstName<span class="punctuation token">;</span>
<span class="punctuation token">}</span><span class="punctuation token">;</span>
Person<span class="punctuation token">.</span>prototype<span class="punctuation token">.</span>sayHello <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span>
console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">"Hello, I'm "</span> <span class="operator token">+</span> <span class="keyword token">this</span><span class="punctuation token">.</span>firstName<span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="punctuation token">}</span><span class="punctuation token">;</span>
<span class="keyword token">var</span> person1 <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Person</span><span class="punctuation token">(</span><span class="string token">"Alice"</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="keyword token">var</span> person2 <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Person</span><span class="punctuation token">(</span><span class="string token">"Bob"</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="keyword token">var</span> helloFunction <span class="operator token">=</span> person1<span class="punctuation token">.</span>sayHello<span class="punctuation token">;</span>
<span class="comment token">// logs "Hello, I'm Alice"</span>
person1<span class="punctuation token">.</span><span class="function token">sayHello</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="comment token">// logs "Hello, I'm Bob"</span>
person2<span class="punctuation token">.</span><span class="function token">sayHello</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="comment token">// logs "Hello, I'm undefined" (or fails</span>
<span class="comment token">// with a TypeError in strict mode)</span>
<span class="function token">helloFunction</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="comment token">// logs true</span>
console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>helloFunction <span class="operator token">===</span> person1<span class="punctuation token">.</span>sayHello<span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="comment token">// logs true</span>
console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>helloFunction <span class="operator token">===</span> Person<span class="punctuation token">.</span>prototype<span class="punctuation token">.</span>sayHello<span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="comment token">// logs "Hello, I'm Alice"</span>
helloFunction<span class="punctuation token">.</span><span class="function token">call</span><span class="punctuation token">(</span>person1<span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre>
<p>Come dimostra questo esempio tutti i riferimenti alla funzione <code>sayHello</code> — quello su <code>person1</code>, su <code>Person.prototype</code>, nella variabile <code>helloFunction</code>, ecc.— si riferiscono tutti alla <em>stessa funzione</em>. Il valore di <code>this</code> nel corso di una chiamata alla funzione dipende da come noi lo chiamiamo. Più comunemente, quando chiamiamo <code>this</code> in un'espressione dove abbiamo ottenuto la funzione da una proprietà di oggetto — <code>person1.sayHello()</code>— <code>this</code> è riferito all'oggetto da cui abbiamo ottenuto la funzione (<code>person1</code>), questa è la ragione per cui <code>person1.sayHello()</code> usa il nome "Alice" e <code>person2.sayHello()</code> usa il nome "Bob". Ma se lo chiamiamo in altri modi, <code>this</code> è impostato in modo diverso: chiamare <code>this</code> da una variabile— <code>helloFunction()</code>— <code>imposta this</code> come riferimento all'oggetto globale (<code>window</code>, sui browser). Dal momento che l'oggetto globale (probabilmente) non dispone di una proprietà <code>firstName</code> otteniamo "Hello, I'm undefined". (Questo accade in modalità blanda (loose mode); sarebbe stato diverso [un errore] in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode" title="/en/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode">strict mode</a>, ma per evitare confusione qui non entreremo nei dettagli). Oppure si può impostare <code>this</code> esplicitamente utilizzando <code>Function#call</code> (o <code>Function#apply</code>), come illustrato alla fine dell'esempio.</p>
<div class="note"><strong>Nota:</strong> Vedi approfondimenti su <code>this</code> in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call">Function#call</a> e <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply">Function#apply</a></div>
<h4 id="Eredità">Eredità</h4>
<p>L'ereditarietà è un modo per creare una classe come una versione specializzata di una o più classi (<em>JavaScript supporta solo l'ereditarietà singola</em>). La classe specializzata viene comunemente chiamata <em>figlio</em>, e l'altra classe viene comunemente chiamato <em>padre</em>. In JavaScript si esegue questa operazione assegnando un'istanza della classe padre alla classe figlio, e poi specializzandola. Nel browser moderni è anche possibile utilizzare <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Classical_inheritance_with_Object.create" title="/en-US/docs/JavaScript/Reference/Global_Objects/Object/create#Classical_inheritance_with_Object.create">Object.create</a> per implementare l'ereditarietà.</p>
<div class="note">
<p><strong>Nota:</strong> JavaScript non rileva <code>prototype.constructor</code> della classe figlio (vedi <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype">Object.prototype</a>), quindi devi farlo manualmente. Vedi la domanda "<a href="http://stackoverflow.com/questions/8453887/why-is-it-necessary-to-set-the-prototype-constructor">Why is it necessary to set the prototype constructor?</a>" su Stackoverflow.</p>
</div>
<p>Nell'esempio seguente definiamo la classe <code>Student</code> come classe figlio di <code>Person</code>. Quindi ridefiniamo il metodo <code>sayHello()</code> e aggiungiamo il metodo <code>sayGoodBye()</code> .</p>
<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// Define the Person constructor</span>
<span class="keyword token">var</span> Person <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span>firstName<span class="punctuation token">)</span> <span class="punctuation token">{</span>
<span class="keyword token">this</span><span class="punctuation token">.</span>firstName <span class="operator token">=</span> firstName<span class="punctuation token">;</span>
<span class="punctuation token">}</span><span class="punctuation token">;</span>
<span class="comment token">// Add a couple of methods to Person.prototype</span>
Person<span class="punctuation token">.</span>prototype<span class="punctuation token">.</span>walk <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">{</span>
console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">"I am walking!"</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="punctuation token">}</span><span class="punctuation token">;</span>
Person<span class="punctuation token">.</span>prototype<span class="punctuation token">.</span>sayHello <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">{</span>
console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">"Hello, I'm "</span> <span class="operator token">+</span> <span class="keyword token">this</span><span class="punctuation token">.</span>firstName<span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="punctuation token">}</span><span class="punctuation token">;</span>
<span class="comment token">// Define the Student constructor</span>
<span class="keyword token">function</span> <span class="function token">Student</span><span class="punctuation token">(</span>firstName<span class="punctuation token">,</span> subject<span class="punctuation token">)</span> <span class="punctuation token">{</span>
<span class="comment token">// Call the parent constructor, making sure (using Function#call)</span>
<span class="comment token">// that "this" is set correctly during the call</span>
Person<span class="punctuation token">.</span><span class="function token">call</span><span class="punctuation token">(</span><span class="keyword token">this</span><span class="punctuation token">,</span> firstName<span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="comment token">// Initialize our Student-specific properties</span>
<span class="keyword token">this</span><span class="punctuation token">.</span>subject <span class="operator token">=</span> subject<span class="punctuation token">;</span>
<span class="punctuation token">}</span><span class="punctuation token">;</span>
<span class="comment token">// Create a Student.prototype object that inherits from Person.prototype.</span>
<span class="comment token">// Note: A common error here is to use "new Person()" to create the</span>
<span class="comment token">// Student.prototype. That's incorrect for several reasons, not least </span>
<span class="comment token">// that we don't have anything to give Person for the "firstName" </span>
<span class="comment token">// argument. The correct place to call Person is above, where we call </span>
<span class="comment token">// it from Student.</span>
Student<span class="punctuation token">.</span>prototype <span class="operator token">=</span> Object<span class="punctuation token">.</span><span class="function token">create</span><span class="punctuation token">(</span>Person<span class="punctuation token">.</span>prototype<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// See note below</span>
<span class="comment token">// Set the "constructor" property to refer to Student</span>
Student<span class="punctuation token">.</span>prototype<span class="punctuation token">.</span>constructor <span class="operator token">=</span> Student<span class="punctuation token">;</span>
<span class="comment token">// Replace the "sayHello" method</span>
Student<span class="punctuation token">.</span>prototype<span class="punctuation token">.</span>sayHello <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">{</span>
console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">"Hello, I'm "</span> <span class="operator token">+</span> <span class="keyword token">this</span><span class="punctuation token">.</span>firstName <span class="operator token">+</span> <span class="string token">". I'm studying "</span>
<span class="operator token">+</span> <span class="keyword token">this</span><span class="punctuation token">.</span>subject <span class="operator token">+</span> <span class="string token">"."</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="punctuation token">}</span><span class="punctuation token">;</span>
<span class="comment token">// Add a "sayGoodBye" method</span>
Student<span class="punctuation token">.</span>prototype<span class="punctuation token">.</span>sayGoodBye <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">{</span>
console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">"Goodbye!"</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="punctuation token">}</span><span class="punctuation token">;</span>
<span class="comment token">// Example usage:</span>
<span class="keyword token">var</span> student1 <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Student</span><span class="punctuation token">(</span><span class="string token">"Janet"</span><span class="punctuation token">,</span> <span class="string token">"Applied Physics"</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
student1<span class="punctuation token">.</span><span class="function token">sayHello</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// "Hello, I'm Janet. I'm studying Applied Physics."</span>
student1<span class="punctuation token">.</span><span class="function token">walk</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// "I am walking!"</span>
student1<span class="punctuation token">.</span><span class="function token">sayGoodBye</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// "Goodbye!"</span>
<span class="comment token">// Check that instanceof works correctly</span>
console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>student1 <span class="keyword token">instanceof</span> <span class="class-name token">Person</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// true </span>
console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>student1 <span class="keyword token">instanceof</span> <span class="class-name token">Student</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// true</span></code></pre>
<p>Per quanto riguarda la linea <code>Student.prototype = Object.create(Person.prototype);</code> : in vecchi interpreti JavaScript senza <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create" title="Object.create"><code>Object.create</code></a>, si può utilizzare un "polyfill" (anche detto "shim", vedi l'articolo collegato), oppure utilizzare una funzione che produce il medesimo risultato, come:</p>
<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">function</span> <span class="function token">createObject</span><span class="punctuation token">(</span>proto<span class="punctuation token">)</span> <span class="punctuation token">{</span>
<span class="keyword token">function</span> <span class="function token">ctor</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> <span class="punctuation token">}</span>
ctor<span class="punctuation token">.</span>prototype <span class="operator token">=</span> proto<span class="punctuation token">;</span>
<span class="keyword token">return</span> <span class="keyword token">new</span> <span class="class-name token">ctor</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="punctuation token">}</span>
<span class="comment token">// Usage:</span>
Student<span class="punctuation token">.</span>prototype <span class="operator token">=</span> <span class="function token">createObject</span><span class="punctuation token">(</span>Person<span class="punctuation token">.</span>prototype<span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre>
<div class="note"><strong>Nota:</strong> Vedi <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create" title="Object.create">Object.create</a> per maggiori informazioni su ciò che fa uno shim per vecchi interpreti.</div>
<p>Essere sicuri che <code>this</code> punti alla cosa giusta a prescindere da come l'oggetto sia istanziato può essere difficile. Tuttavia c'e una tecnica semplice per renderlo più facile.</p>
<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">var</span> Person <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span>firstName<span class="punctuation token">)</span> <span class="punctuation token">{</span>
<span class="keyword token">if</span> <span class="punctuation token">(</span><span class="keyword token">this</span> <span class="keyword token">instanceof</span> <span class="class-name token">Person</span><span class="punctuation token">)</span> <span class="punctuation token">{</span>
<span class="keyword token">this</span><span class="punctuation token">.</span>firstName <span class="operator token">=</span> firstName<span class="punctuation token">;</span>
<span class="punctuation token">}</span> <span class="keyword token">else</span> <span class="punctuation token">{</span>
<span class="keyword token">return</span> <span class="keyword token">new</span> <span class="class-name token">Person</span><span class="punctuation token">(</span>firstName<span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="punctuation token">}</span>
<span class="punctuation token">}</span></code></pre>
<h4 id="Incapsulamento">Incapsulamento</h4>
<p>Nell'esempio precedente <code>Student</code> non ha bisogno di sapere come sia realizzato il metodo <code>walk()</code> della classe <code>Person</code>, ma può comunque utilizzarlo; la classe <code>Student</code> non ha bisogno di definire in modo esplicito questo metodo se non vogliamo cambiarlo. Questo è chiamato <strong>incapsulamento</strong>, per cui ogni classe impacchetta dati e metodi in una singola unità.</p>
<p>Il nascondere informazioni (information hiding) è una caratteristica comune ad altre linguaggi, spesso in forma di metodi / proprietà private e protette. Anche se si potrebbe simulare qualcosa di simile in JavaScript, questo non è un requisito per fare programmazione Object Oriented.<a href="https://developer.mozilla.org/it/docs/Web/JavaScript/Introduzione_al_carattere_Object-Oriented_di_JavaScript$edit#cite-2"><sup>2</sup></a></p>
<h4 id="Astrazione">Astrazione</h4>
<p>L'astrazione è un meccanismo che permette di modellare la parte corrente del problema, sia con eredità (specializzazione) o la composizione. JavaScript ottiene la specializzazione per eredità, e la composizione permettendo che istanze di classe siano valori di attributi di altri oggetti.</p>
<p>La classe Function di Javascript eredita dalla classe Object (questo dimostra la specializzazione del modello) e la proprietà Function.prototype è un'istanza di oggetto (ciò dimostra la composizione).</p>
<p>The JavaScript Function class inherits from the Object class (this demonstrates specialization of the model) and the Function.prototype property is an instance of Object (this demonstrates composition).</p>
<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">var</span> foo <span class="operator token">=</span> <span class="keyword token">function</span> <span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span><span class="punctuation token">}</span><span class="punctuation token">;</span>
<span class="comment token">// logs "foo is a Function: true"</span>
console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">'foo is a Function: '</span> <span class="operator token">+</span> <span class="punctuation token">(</span>foo <span class="keyword token">instanceof</span> <span class="class-name token">Function</span><span class="punctuation token">)</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="comment token">// logs "foo.prototype is an Object: true"</span>
console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">'foo.prototype is an Object: '</span> <span class="operator token">+</span> <span class="punctuation token">(</span>foo<span class="punctuation token">.</span>prototype <span class="keyword token">instanceof</span> <span class="class-name token">Object</span><span class="punctuation token">)</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre>
<h4 id="Polimorfismo">Polimorfismo</h4>
<p>Così come tutti i metodi e le proprietà sono definite all'interno della proprietà prototype, classi diverse possono definire metodi con lo stesso nome; i metodi sono nell'ambito della classe in cui sono definiti, a meno che le due classi siano in un rapporto padre-figlio (cioè una eredita dall'altra in una catena di ereditarietà).</p>
<h2 id="Notes" name="Notes">Note</h2>
<p>Le tecniche presentate in questo articolo per attuare la programmazione orientata agli oggetti non sono le uniche che possono essere utilizzate in JavaScript, che è molto flessibile in termini di come la programmazione orientata agli oggetti possa essere eseguita.</p>
<p>Allo stesso modo, le tecniche qui indicate non usano alcuna violazione di linguaggio, né imitano implementazioni di teorie di oggetti di altri linguaggi.</p>
<p>Ci sono altre tecniche che rendono la programmazione orientata agli oggetti in JavaScript ancora più avanzata, ma sono oltre la portata di questo articolo introduttivo.</p>
<h2 id="References" name="References">Riferimenti</h2>
<ol>
<li>{{ Ref() }} Mozilla. "Core JavaScript 1.5 Guide", http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide</li>
<li>{{ Ref() }} wikipedia. "Object-oriented programming", <a class="external" href="http://en.wikipedia.org/wiki/Object-oriented_programming" rel="freelink">http://en.wikipedia.org/wiki/Object-...ed_programming</a></li>
</ol>
<div class="originaldocinfo">
<p><strong>Original Document Information</strong></p>
<ul>
<li>Author(s): Fernando Trasviña <f_trasvina at hotmail dot com></li>
<li>Copyright Information: © 1998-2005 by individual mozilla.org contributors; content available under a <a class="external" href="http://www.mozilla.org/foundation/licensing/website-content.html">Creative Commons license</a></li>
</ul>
</div>
<p>{{ languages( { "es": "es/Introducción_a_JavaScript_orientado_a_objetos"} ) }}</p>
|