JS 學習ES6之 class 的繼承

2021-08-20 17:34:45 字數 2915 閱讀 8619

class 可以通過extends關鍵字實現繼承。

在子類繼承父類的時候,在constructor中必須首先呼叫super()方法,然後才能使用this

// 父類

class point

tostring()

}// 子類

class colorpoint extends point

tostring()

}

子類必須在constructor方法中呼叫super方法,否則新建例項時會報錯。這是因為子類自己的this物件,必須先通過父類的建構函式完成塑造,得到與父類同樣的例項屬性和方法,然後再對其進行加工,加上子類自己的例項屬性和方法。如果不呼叫super方法,子類就得不到this物件。

父類的靜態方法,也會被子類繼承。

class a 

}class b extends a

b.hello() // hello world

上面**中,hello()a類的靜態方法,b繼承a,也繼承了a的靜態方法。

object.getprototypeof方法可以用來從子類上獲取父類。

object.getprototypeof(colorpoint) === point

// true

因此,可以使用這個方法判斷,乙個類是否繼承了另乙個類。

super這個關鍵字,既可以當作函式使用,也可以當作物件使用。

第一種情況,super作為函式呼叫時,代表父類的建構函式。

class a {}

class b extends a

}

第二種情況,super作為物件時,在普通方法中,指向父類的原型物件;在靜態方法中,指向父類。

class a 

}class b extends a

}let b = new b();

上面**中,子類b當中的super.p(),就是將super當作乙個物件使用。這時,super在普通方法之中,指向a.prototype,所以super.p()就相當於a.prototype.p()

這裡需要注意,由於super指向父類的原型物件,所以定義在父類例項上的方法或屬性,是無法通過super呼叫的。

class a 

}class b extends a

}let b = new b();

b.m // undefined

上面**中,p是父類a例項的屬性,super.p就引用不到它。

es6 規定,在子類普通方法中通過super呼叫父類的方法時,方法內部的this指向當前的子類例項。

class a 

print()

}class b extends a

m()}let b = new b();

b.m(); // 2

上面**中,super.print()雖然呼叫的是a.prototype.print(),但是a.prototype.print()內部的this指向子類b的例項,導致輸出的是2,而不是1。也就是說,實際上執行的是super.print.call(this)

如果super作為物件,用在靜態方法之中,這時super將指向父類,而不是父類的原型物件。

class parent 

mymethod(msg)

}class child extends parent

mymethod(msg)

}child.mymethod(1); // static 1

var child = new child();

child.mymethod(2); // instance 2

上面**中,super在靜態方法之中指向父類,在普通方法之中指向父類的原型物件。

另外,在子類的靜態方法中通過super呼叫父類的方法時,方法內部的this指向當前的子類,而不是子類的例項。

class a 

static print()

}class b extends a

static m()

}b.x = 3;

b.m() // 3

上面**中,靜態方法b.m裡面,super.print指向父類的靜態方法。這個方法裡面的this指向的是b,而不是b的例項。

ES6之Class學習筆記

prototype 是類或者方法的 方法,proto 是new 之後的例項的方法。constructor方法是類的預設方法,通過new命令生成物件例項時,自動呼叫該方法。乙個類必須有constructor方法,如果沒有顯式定義,乙個空的constructor方法會被預設新增。class point ...

ES6之 Class 的繼承(十二)

super關鍵字 class colorpoint extends point tostring 如果不呼叫super方法,子類就得不到this物件 class point class colorpoint extends point let cp newcolorpoint referenceer...

ES6之 class的基本語法(類)

es6之前,我們都是通過建構函式來生成例項物件 function point x,y point prototype.sum function let point newpoint 1 2 console.log point.sum 3es6 提供了更接近傳統語言的寫法,引入了 class 類 這個...