extends
La parola chiave extends è utilizzata nella dichiarazione o espressione di classe per creare una classe figlia di un'altra classe.
Sintassi
class ChildClass extends ParentClass { ... }
/**
*@desc La classe ChildClass estende la classe ParentClass
*/
Descrizione
La parola chiave extends può essere utilizzata per creare una sottoclasse personalizzata basandosi su classi già esistenti e anche su oggetti nativi (cfr. Date object).
Il .prototype dell'estensione deve essere un Object oppure null.
Esempi
Utilizzare extends
Il primo esempio crea una classe chiamata Square dalla classe chiamata Polygon. Questo esempio è estratto da questo demo live (sorgente).
class Square extends Polygon {
constructor(length) {
// Qui chiama il constructor della classe che estende (parent)
// con le misure per la larghezza e altezza del poligono
super(length, length);
// Nota: In classi derivate, super() deve essere chiamato prima
// di poter utilizzare 'this', altrimenti causerà un errore di reference.
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
set area(value) {
this.height = this.width = Math.sqrt(value);
this.area = value;
}
}Utilizzare extends con oggetti nativi
Questo esempio estende l'oggetto nativo Date. Questo esempio è estratto da questo demo live (sorgente).
class myDate extends Date {
constructor() {
super();
}
getFormattedDate() {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return this.getDate() + '-' + months[this.getMonth()] + '-' + this.getFullYear();
}
}Estendere null
Estendere da null funziona come di norma, eccetto che l'oggetto prototipo non eredita da Object.prototype.
class nullExtends extends null {
constructor() {}
}
Object.getPrototypeOf(nullExtends); // Function.prototype
Object.getPrototypeOf(nullExtends.prototype) // nullSpecificazioni
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'extends' in that specification. |
Standard | Initial definition. |
| ECMAScript (ECMA-262) The definition of 'extends' in that specification. |
Living Standard |
Compatibilità 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! (en-US)
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | 42.0 | 45 (45) | ? | ? | ? |
| Array subclassing | 43.0 | No support | ? | ? | ? |
| Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
|---|---|---|---|---|---|---|
| Basic support | No support | 45.0 (45) | ? | ? | ? | 42.0 |
| Array subclassing | No support | No support | ? | ? | ? | 43.0 |

