此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。
extends
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2016年3月.
extends 關鍵字被使用於類別(class)宣告或類別(class)表達式中來建立擴展的子類別 。
In this article
嘗試一下
class DateFormatter extends Date { getFormattedDate() { const months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ]; return `${this.getDate()}-${months[this.getMonth()]}-${this.getFullYear()}`; }}console.log(new DateFormatter("August 19, 1975 23:15:30").getFormattedDate());// Expected output: "19-Aug-1975"語法
class ChildClass extends ParentClass { ... }解釋
extends 關鍵字可用於建立一個自訂類別或內建類別的子類別。
範例
>使用extends
第一個範例是根據Polygon類別建立一個名為Square 的子類別。此範例提取自線上示例。
js
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 於內建類別
js
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
像擴展普通類別一樣擴展null,但新對象的原型不會繼承Object.prototype。
js
class nullExtends extends null { constructor() {}}Object.getPrototypeOf(nullExtends); // Function.prototypeObject.getPrototypeOf(nullExtends.prototype); // nullnew nullExtends(); //ReferenceError: this is not defined標準
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-class-definitions> |