Słowo kluczowe extends
jest używane w deklaracjach klas lub wyrażeniach class do tworzenia klasy jako elementu potomnego innej klasy.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Składnia
class ChildClass extends ParentClass { ... }
Opis
Słowo kluczowe extends
może być użyte do dziedziczenia po niestandardowych klasach lub standardowych obiektach wbudowanych.
Przykłady
Zastosowanie extends
Pierwszy przykład tworzy klasę Square
rozszerzającą klasę Polygon
. live demo (source).
class Square extends Polygon {
constructor(length) {
// Wywołanie konstruktora klasy nadrzędnej
// określenie szerokości i wysokości wielokątu
super(length, length);
// Uwaga: W pochodnych klasach, super() musi być wywołane wcześniej niż
// pierwsze użycie 'this'. W przeciwnym wypadku pojawi się błąd odniesienia.
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
}
Zastosowanie extends z obiektami wbudowanymi
Poniższy przykład rozszerza wbudowany obiekt Date
. live demo (source).
class myDate extends Date {
getFormattedDate() {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return this.getDate() + '-' + months[this.getMonth()] + '-' + this.getFullYear();
}
}
Specyfikacje
Kompatybilność
BCD tables only load in the browser
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.