ๆญค้ ้ข็”ฑ็คพ็พคๅพž่‹ฑๆ–‡็ฟป่ญฏ่€Œไพ†ใ€‚ไบ†่งฃๆ›ดๅคšไธฆๅŠ ๅ…ฅ MDN Web Docs ็คพ็พคใ€‚

View in English Always switch to English

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๏ผ‰่กจ้”ๅผไธญไพ†ๅปบ็ซ‹ๆ“ดๅฑ•็š„ๅญ้กžๅˆฅ ใ€‚

ๅ˜—่ฉฆไธ€ไธ‹

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 ้—œ้ตๅญ—ๅฏ็”จๆ–ผๅปบ็ซ‹ไธ€ๅ€‹่‡ช่จ‚้กžๅˆฅๆˆ–ๅ…งๅปบ้กžๅˆฅ็š„ๅญ้กžๅˆฅใ€‚

ๅ…ถ็นผๆ‰ฟไน‹ๅŽŸๅž‹ .prototype ๅฟ…้ ˆๆ˜ฏ Object ๆˆ– nullใ€‚

็ฏ„ไพ‹

ไฝฟ็”จ 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 ๆ–ผๅ…งๅปบ้กžๅˆฅ

้€™ๅ€‹็ฏ„ไพ‹ๆ“ดๅฑ•ไบ†ๅ…งๅปบ็š„ Date ้กžๅˆฅใ€‚ๆญค็ฏ„ไพ‹ๆๅ–่‡ช็ทšไธŠ็ฏ„ไพ‹ใ€‚

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.prototype
Object.getPrototypeOf(nullExtends.prototype); // null

new nullExtends(); //ReferenceError: this is not defined

ๆจ™ๆบ–

Specification
ECMAScriptยฎ 2026 Language Specification
# sec-class-definitions

็€่ฆฝๅ™จ็›ธๅฎนๆ€ง

ๅƒ่ฆ‹