本文實例講述了ES6 javascript中Class類繼承用法。分享給大家供大家參考,具體如下:
1. 基本用法
Class 之間可以通過extends關鍵字實現繼承, 這比 ES5 的通過修改原型鏈實現繼承, 要清晰和方便很多。
class ColorPoint extends Point {}上面代碼定義了一個ColorPoint類, 該類通過extends關鍵字, 繼承了Point類的所有屬性和方法。 但是由于沒有部署任何代碼, 所以這兩個類完全一樣, 等于復制了一個Point類。 下面, 我們在ColorPoint內部加上代碼。
class ColorPoint extends Point { constructor(x, y, color) { super(x, y); // 調用父類的 constructor(x, y) this.color = color; } toString() { return this.color + ' ' + super.toString(); // 調用父類的 toString() }}上面代碼中, constructor方法和toString方法之中, 都出現了super關鍵字, 它在這里表示父類的構造函數, 用來新建父類的this對象。
子類必須在constructor方法中調用super方法, 否則新建實例時會報錯。 這是因為子類沒有自己的this對象, 而是繼承父類的this對象, 然后對其進行加工。 如果不調用super方法, 子類就得不到this對象。
class Point { /* ... */ }class ColorPoint extends Point { constructor() {}}let cp = new ColorPoint(); // ReferenceError上面代碼中, ColorPoint繼承了父類Point, 但是它的構造函數沒有調用super方法, 導致新建實例時報錯。
ES5 的繼承, 實質是先創造子類的實例對象this, 然后再將父類的方法添加到this上面( Parent.apply(this))。 ES6 的繼承機制完全不同, 實質是先創造父類的實例對象this( 所以必須先調用super方法), 然后再用子類的構造函數修改this。
如果子類沒有定義constructor方法, 這個方法會被默認添加, 代碼如下。 也就是說, 不管有沒有顯式定義, 任何一個子類都有constructor方法。
constructor(...args) { super(...args);}另一個需要注意的地方是, 在子類的構造函數中, 只有調用super之后, 才可以使用this關鍵字, 否則會報錯。 這是因為子類實例的構建, 是基于對父類實例加工, 只有super方法才能返回父類實例。
class Point { constructor(x, y) { this.x = x; this.y = y; }}class ColorPoint extends Point { constructor(x, y, color) { this.color = color; // ReferenceError super(x, y); this.color = color; // 正確 }}上面代碼中, 子類的constructor方法沒有調用super之前, 就使用this關鍵字, 結果報錯, 而放在super方法之后就是正確的。
下面是生成子類實例的代碼。
let cp = new ColorPoint(25, 8, 'green');cp instanceof ColorPoint // truecp instanceof Point // true
新聞熱點
疑難解答
圖片精選