Class可以透過extend關鍵字實現繼承。super關鍵字表示父類的建構函式,用來新建父類的this物件。
子類須在constructor方法中呼叫super方法,這樣才能得到父類的this,否則會報錯。這是因為子類自己的this物件,必須先透過父類的建構函式完成塑造,得到與父類同樣的例項屬性和方法,然後再對其進行加工,加上子類自己的例項屬性和方法。
呼叫函式使用的例子
class A {
constructor() {
console.log(new.target.name);
}
class B extends A {
super();
new A() // A
new B() // B
擴充套件資料
例項屬性的新寫法
class IncreasingCounter {
constructor()
{
this._count = 0;
_count = 0; //_count定義在類的最頂層與上面的constructor()寫法等價
get value() {
console.log("Getting the current value!");
return this._count;
increment()
this._count++;
Class可以透過extend關鍵字實現繼承。super關鍵字表示父類的建構函式,用來新建父類的this物件。
子類須在constructor方法中呼叫super方法,這樣才能得到父類的this,否則會報錯。這是因為子類自己的this物件,必須先透過父類的建構函式完成塑造,得到與父類同樣的例項屬性和方法,然後再對其進行加工,加上子類自己的例項屬性和方法。
呼叫函式使用的例子
class A {
constructor() {
console.log(new.target.name);
}
}
class B extends A {
constructor() {
super();
}
}
new A() // A
new B() // B
擴充套件資料
例項屬性的新寫法
class IncreasingCounter {
constructor()
{
this._count = 0;
}
_count = 0; //_count定義在類的最頂層與上面的constructor()寫法等價
get value() {
console.log("Getting the current value!");
return this._count;
}
increment()
{
this._count++;
}
}