Il metodo constructor
è un metodo speciale usato per la creazione e l'inizializzazione di un oggetto creato da una classe
.
Sintassi
constructor([argomenti]) { ... }
Descrizione
In una classe ci può essere un solo metodo con il nome "constructor". Se una classe contiene una o più occorrenze del metodo constructor
viene sollevato un errore di tipo SyntaxError
.
Un costruttore può usare la keyword super
per chiamare il costruttore di una classe genitore.
Se non viene specificato un metodo constructor
, verrà usato quello di default.
Esempi
Usare il metodo constructor
Questo pezzo di codice è stato preso da classes sample (live demo).
class Square extends Polygon {
constructor(length) {
// Chiama il costruttore della classe padre usando lo stesso valore length
// come altezza e come larghezza del Poligono
super(length, length);
// Nota: Nelle classi derivate, super() deve essere chiamato prima
// dell'utilizzo di 'this', altrimenti viene sollevato un reference error.
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
set area(value) {
this.area = value;
}
}
Costruttori predefinito
Se non viene specificato un metodo costruttore, verrà usato quello di default. Per le classi base il costruttore di default è:
constructor() {}
Per le classi derivate invece è:
constructor(...args) {
super(...args);
}
Specifiche
Specifica | Stato | Commento |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Constructor Method' in that specification. |
Standard | Initial definition. |
ECMAScript (ECMA-262) The definition of 'Constructor Method' in that specification. |
Living Standard |
Compatibilità con i Browser
We're converting our compatibility data into a machine-readable JSON format.
This compatibility table still uses the old format,
because we haven't yet converted the data it contains.
Find out how you can help!
Specifica | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Supporto Base | 42.0 | 45 (45) | ? | ? | ? |
Costruttore predefinito | ? | 45 (45) | ? | ? | ? |
Specifica | Android | Android Webview | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome per Android |
---|---|---|---|---|---|---|---|
Supporto Base | No support | 42.0 | 45.0 (45) | ? | ? | ? | 42.0 |
Costruttore predefinito | ? | ? | 45.0 (45) | ? | ? | ? | ? |