類的繼承:extends
關鍵字用於類聲明或者類表達式中,以創建一個類,該類是另一個類的子類。
extends
關鍵字用來創建一個普通類或者內建對象的子類。
繼承一個類:
class Foo {
constructor(){
this.a = 1;
}
func1(){
console.log("func1");
}
}
class Bar extends Foo{
constructor(){
super();
this.b = 2;
}
func2(){
console.log("func2");
}
}
var bar = new Bar();
console.log(bar);
拓展一個內置對象:
class myDate extends Date{
constructor(){
super();
this.name = "myDate";
}
func(){
console.log("拓展內置對象Date");
}
}
var date = new myDate();
console.log(date,date.name);Wed Jul 01 2020 14:31:36 GMT+0800 (中國標準時間) "myDate"
date.func() 拓展內置對象Date
super方法
必須在constructor中先執行super方法,必須將super方法執行寫在constructor最前面
以下的代碼會報錯,當創建bar新的對象的時候,執行new Bar()時,會報錯。this是undefined。
class Foo {
constructor(){
this.a = 1;
}
func1(){
console.log("func1");
}
}
class Bar extends Foo{
constructor(){
this.c = 3; 報錯:this是undefined
super();
this.b = 2;
}
func2(){
console.log("func2");
}
}
var bar = new Bar();
子類繼承父類的靜態方法
class Foo {
constructor(){
this.a = 1;
}
static func(){
console.log("father static function")
}
func1(){
console.log("func1");
}
}
class Bar extends Foo{
constructor(){
super();
this.b = 2;
this.c = 3;
}
func2(){
console.log("func2");
Bar.func();//子類可以繼承父類的靜態方法func
}
}
var bar = new Bar();
console.log(bar); Bar {a: 1, b: 2, c: 3}
bar.func2(); 執行func2函數,又執行了func函數
也可以繼承靜態屬性:靜態屬性設置寫在子類前,或子類後都是可以,但是一定要在實例對象創建前。
class Foo {
constructor(){
this.a = 1;
}
static func(){
console.log("father static function")
}
func1(){
console.log("func1");
}
}
class Bar extends Foo{
constructor(){
super();
this.b = 2;
this.c = 3;
}
func2(){
console.log(Bar.prop);
}
}
Foo.prop = "static prop";
var bar = new Bar();
console.log(bar);
bar.func2(); 打印:static prop