--- title: extends slug: Web/JavaScript/Reference/Classes/extends tags: - JavaScript наследяване - Класове - наследяване translation_of: Web/JavaScript/Reference/Classes/extends ---
Ключовата дума extends се използва в декларацията на класове или класовите изрази за създаване на клас, който е дете на друг клас.
class ChildClass extends ParentClass { ... }
Ключовата дума extends може да бъде използвана като подклас на потребителски класове, както и за вградени обекти.
Прототипът (.prototype) на разширението трябва да е {{jsxref("Object")}} или {{jsxref("null")}}.
extendsПървият пример създава клас, наречен Square от клас, наречен Polygon (Square класът наследява клас Polygon ). Този пример е взет от това демо на живо (източник).
class Square extends Polygon {
constructor(length) {
// Here, it calls the parent class' constructor with lengths
// provided for the Polygon's width and height
super(length, length);
// Note: In derived classes, super() must be called before you
// can use 'this'. Leaving this out will cause a reference error.
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
}
extends с вградени обектиТози пример разширява вграденият {{jsxref("Date")}} обект. Този пример е взет от това демо на живо (източник).
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();
}
}
nullНаследяване от {{jsxref("null")}} работи както при нормалните класове, eс изключение на това , че обектът на прототипа не наследява от {{jsxref("Object.prototype")}}.
class nullExtends extends null {
constructor() {}
}
Object.getPrototypeOf(nullExtends); // Function.prototype
Object.getPrototypeOf(nullExtends.prototype) // null
new nullExtends(); //ReferenceError: this is not defined
| Спецификации | Статус | Коментар |
|---|---|---|
| {{SpecName('ES2015', '#sec-class-definitions', 'extends')}} | {{Spec2('ES2015')}} | Initial definition. |
| {{SpecName('ESDraft', '#sec-class-definitions', 'extends')}} | {{Spec2('ESDraft')}} |
{{Compat("javascript.classes.extends")}}