extends 關鍵字用於類別宣告或運算式,可建立 做為另一個子類別的類別,並包含父項類別 (有時候 稱為「基礎類別」) 做為子項類別的原型 (有時候 稱為「子類別」或「衍生類別」)。
class ParentClass {} class ChildClass extends ParentClass {} Object.getPrototypeOf( ChildClass ); > class ParentClass {} 這些子類別會繼承父項類別的屬性和方法。這個 可以擴充類別的核心功能, 不必將父項類別超載來配合所有可能的用途 或重新實作具有類似用途的程式碼
子項類別可提供自己的繼承方法實作 父類別:
class MyClass { constructor( myPassedValue ) { this.instanceProp = myPassedValue; } classMethod() { console.log( `The value was '${ this.instanceProp }.'`) } } class ChildClass extends MyClass { classMethod() { console.log( `The value was '${ this.instanceProp },' and its type was '${ typeof this.instanceProp }.'`) } } const myParentClassInstance = new MyClass( "My string." ); const mySubclassInstance = new ChildClass( 100 ); myParentClassInstance.classMethod(); > "The value type was 'string.'" mySubclassInstance.classMethod(); > "The value was '100,' and its type was 'number.'" 您也可以呼叫 使用 super 的子項類別:
class MyClass { constructor( myPassedValue ) { this.instanceProp = myPassedValue; } classMethod() { console.log( `The value was '${ this.instanceProp }.'`) } } class ChildClass extends MyClass { subclassMethod() { super.classMethod(); console.log( `The value type was '${ typeof this.instanceProp }.'`) } } const mySubclassInstance = new ChildClass( 100 ); mySubclassInstance.subclassMethod(); > The value was '100.' > The value type was 'number.' 如上述範例所示,在 constructor() 方法 子項類別的結構定義,JavaScript 的隱含建構函式會呼叫父項 以及同一組引數不過 您必須先呼叫 super(),以及任何 參照 this 之前所有必要的引數。
class MyClass { constructor( myPassedValue ) { this.instanceProp = myPassedValue; } classMethod() { console.log( `The value was '${ this.instanceProp }.'`) } } class ChildClass extends MyClass { constructor( myPassedValue ) { super( myPassedValue ); this.modifiedProp = myPassedValue + 50; }\ subclassMethod() { super.classMethod(); console.log( `The value type was '${ typeof this.instanceProp }.'`) } } const mySubclassInstance = new ChildClass( 100 ); mySubclassInstance; > MyClass { instanceProp: 100, modifiedProp: 150 } getter 和 setter 是專門用於擷取和定義 值。使用 get 和 set 關鍵字定義的方法可讓您 讓您建立可與其互動的方法 資源。
class MyClass { constructor( originalValue ) { this.totalValue = 0; } set doubleThisValue( newValue ) { this.totalValue = newValue * 2; } get currentValue() { console.log( `The current value is: ${ this.totalValue }` ); } } const myClassInstance = new MyClass(); myClassInstance; > MyClass { totalValue: 0 } myClassInstance.doubleThisValue = 20; myClassInstance.currentValue; > The current value is: 40 get 和 set 屬性是在類別的原型屬性上定義, 因此可供該類別的所有執行個體使用
隨堂測驗
針對使用 extends 關鍵字建立的類別,選取正確的敘述。
做為其擴充的類別的子項。
它會繼承其父項類別的屬性和方法。
做為其擴充的類別的父項。
It can't overwrite methods from a parent class.