ES6 | 關於class類 繼承總結

子類必須在constructor方法中調用super方法,不然新建實例時會報錯。這是由於子類沒有本身的this對象,而是繼承父類的this對象,而後對其進行加工。若是不調用super方法,子類就得不到this對象。數組

題圖:by Frank from Instagram瀏覽器

一、class類的繼承數據結構

Class 能夠經過extends關鍵字實現繼承,這比 ES5 的經過修改原型鏈實現繼承,要清晰和方便不少。app

1 class Point {
2 }
3 
4 class ColorPoint extends Point {
5 }

上面代碼定義了一個ColorPoint類,該類經過extends關鍵字,繼承了Point類的全部屬性和方法。可是因爲沒有部署任何代碼,因此這兩個類徹底同樣,等於複製了一個Point類。下面,咱們在ColorPoint內部加上代碼。ide

 1 class ColorPoint extends Point {
 2   constructor(x, y, color) {
 3     super(x, y); // 調用父類的constructor(x, y)
 4     this.color = color;
 5   }
 6 
 7   toString() {
 8     return this.color + ' ' + super.toString(); // 調用父類的toString()
 9   }
10 }

上面代碼中,constructor方法和toString方法之中,都出現了super關鍵字,它在這裏表示父類的構造函數,用來新建父類的this對象。函數

子類必須在constructor方法中調用super方法,不然新建實例時會報錯。這是由於子類沒有本身的this對象,而是繼承父類的this對象,而後對其進行加工。若是不調用super方法,子類就得不到this對象。this

1 class Point { /* ... */ }
2 
3 class ColorPoint extends Point {
4   constructor() {
5   }
6 }
7 
8 let cp = new ColorPoint(); // ReferenceError

上面代碼中,ColorPoint繼承了父類Point,可是它的構造函數沒有調用super方法,致使新建實例時報錯。spa

ES5 的繼承,實質是先創造子類的實例對象this,而後再將父類的方法添加到this上面(Parent.apply(this))。prototype

ES6 的繼承機制徹底不一樣,實質是先創造父類的實例對象this(因此必須先調用super方法),而後再用子類的構造函數修改this3d

若是子類沒有定義constructor方法,這個方法會被默認添加,代碼以下。也就是說,無論有沒有顯式定義,任何一個子類都有constructor方法。

1 class ColorPoint extends Point {
2 }
3 
4 // 等同於
5 class ColorPoint extends Point {
6   constructor(...args) {
7     super(...args);
8   }
9 }

另外一個須要注意的地方是,在子類的構造函數中,只有調用super以後,纔可使用this關鍵字,不然會報錯。

這是由於子類實例的構建,是基於對父類實例加工,只有super方法才能返回父類實例。

 1 class Point {
 2   constructor(x, y) {
 3     this.x = x;
 4     this.y = y;
 5   }
 6 }
 7 
 8 class ColorPoint extends Point {
 9   constructor(x, y, color) {
10     this.color = color; // ReferenceError
11     super(x, y);
12     this.color = color; // 正確
13   }
14 }

上面代碼中,子類的constructor方法沒有調用super以前,就使用this關鍵字,結果報錯,而放在super方法以後就是正確的。

下面是生成子類實例的代碼。

let cp = new ColorPoint(25, 8, 'green');

cp instanceof ColorPoint // true
cp instanceof Point // true

上面代碼中,實例對象cp同時是ColorPointPoint兩個類的實例,這與 ES5 的行爲徹底一致。

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

 1 class A {
 2   static hello() {
 3     console.log('hello world');
 4   }
 5 }
 6 
 7 class B extends A {
 8 }
 9 
10 B.hello()  // hello world

上面代碼中,hello()A類的靜態方法,B繼承A,也繼承了A的靜態方法。


 

二、Object.getPrototypeOf()

Object.getPrototypeOf方法能夠用來從子類上獲取父類。所以,可使用這個方法判斷,一個類是否繼承了另外一個類。

Object.getPrototypeOf(ColorPoint) === Point
// true

三、super 關鍵字

super這個關鍵字,既能夠看成函數使用,也能夠看成對象使用。在這兩種狀況下,它的用法徹底不一樣。

第一種狀況,super做爲函數調用時,表明父類的構造函數。ES6 要求,子類的構造函數必須執行一次super函數。

1 class A {}
2 
3 class B extends A {
4   constructor() {
5     super();
6   }
7 }

上面代碼中,子類B的構造函數之中的super(),表明調用父類的構造函數。這是必須的,不然 JavaScript 引擎會報錯。

注意,super雖然表明了父類A的構造函數,可是返回的是子類B的實例,即super內部的this指的是B,所以super()在這裏至關於A.prototype.constructor.call(this)

 1 class A {
 2   constructor() {
 3     console.log(new.target.name);
 4   }
 5 }
 6 class B extends A {
 7   constructor() {
 8     super();
 9   }
10 }
11 new A() // A
12 new B() // B

上面代碼中,new.target指向當前正在執行的函數。能夠看到,在super()執行時,它指向的是子類B的構造函數,而不是父類A的構造函數。也就是說,super()內部的this指向的是B

做爲函數時,super()只能用在子類的構造函數之中,用在其餘地方就會報錯。

1 class A {}
2 
3 class B extends A {
4   m() {
5     super(); // 報錯
6   }
7 }

上面代碼中,super()用在B類的m方法之中,就會形成句法錯誤。

第二種狀況,super做爲對象時,在普通方法中,指向父類的原型對象A.prototype;在靜態方法中,指向父類。

class A {
  p() {
    return 2;
  }
}

class B extends A {
  constructor() {
    super();
    console.log(super.p()); // 2
  }
}

let b = new B();

上面代碼中,子類B當中的super.p(),就是將super看成一個對象使用。這時,super在普通方法之中,指向A.prototype,因此super.p()就至關於A.prototype.p()

這裏須要注意,因爲super指向父類的原型對象,因此定義在父類實例上的方法或屬性,是沒法經過super調用的。

 1 class A {
 2   constructor() {
 3     this.p = 2;
 4   }
 5 }
 6 
 7 class B extends A {
 8   get m() {
 9     return super.p;
10   }
11 }
12 
13 let b = new B();
14 b.m // undefined

上面代碼中,p是父類A實例的屬性,super.p就引用不到它。

若是屬性定義在父類的原型對象上,super就能夠取到。

 1 class A {}
 2 A.prototype.x = 2;
 3 
 4 class B extends A {
 5   constructor() {
 6     super();
 7     console.log(super.x) // 2
 8   }
 9 }
10 
11 let b = new B();

上面代碼中,屬性x是定義在A.prototype上面的,因此super.x能夠取到它的值。

ES6 規定,在子類普通方法中經過super調用父類的方法時,方法內部的this指向當前的子類實例。

 1 class A {
 2   constructor() {
 3     this.x = 1;
 4   }
 5   print() {
 6     console.log(this.x);
 7   }
 8 }
 9 
10 class B extends A {
11   constructor() {
12     super();
13     this.x = 2;
14   }
15   m() {
16     super.print();
17   }
18 }
19 
20 let b = new B();
21 b.m() // 2

上面代碼中,super.print()雖然調用的是A.prototype.print(),可是A.prototype.print()內部的this指向子類B的實例,致使輸出的是2,而不是1。也就是說,實際上執行的是super.print.call(this)

因爲this指向子類實例,因此若是經過super對某個屬性賦值,這時super就是this,賦值的屬性會變成子類實例的屬性。

 1 class A {
 2   constructor() {
 3     this.x = 1;
 4   }
 5 }
 6 
 7 class B extends A {
 8   constructor() {
 9     super();
10     this.x = 2;
11     super.x = 3;
12     console.log(super.x); // undefined
13     console.log(this.x); // 3
14   }
15 }
16 
17 let b = new B();

上面代碼中,super.x賦值爲3,這時等同於對this.x賦值爲3。而當讀取super.x的時候,讀的是A.prototype.x,因此返回undefined

若是super做爲對象,用在靜態方法之中,這時super將指向父類,而不是父類的原型對象。

 1 class Parent {
 2   static myMethod(msg) {
 3     console.log('static', msg);
 4   }
 5 
 6   myMethod(msg) {
 7     console.log('instance', msg);
 8   }
 9 }
10 
11 class Child extends Parent {
12   static myMethod(msg) {
13     super.myMethod(msg); // 在靜態方法之中指向父類
14   }
15 
16   myMethod(msg) {
17     super.myMethod(msg); // 在普通方法之中指向父類的原型對象
18   }
19 }
20 
21 Child.myMethod(1); // static 1
22 
23 var child = new Child();
24 child.myMethod(2); // instance 2super

上面代碼中,super在靜態方法之中指向父類,在普通方法之中指向父類的原型對象。

另外,在子類的靜態方法中經過super調用父類的方法時,方法內部的this指向當前的子類,而不是子類的實例。

 1 class A {
 2   constructor() {
 3     this.x = 1;
 4   }
 5   static print() {
 6     console.log(this.x);
 7   }
 8 }
 9 
10 class B extends A {
11   constructor() {
12     super();
13     this.x = 2;
14   }
15   static m() {
16     super.print();
17   }
18 }
19 
20 B.x = 3;
21 B.m() // 3

上面代碼中,靜態方法B.m裏面,super.print指向父類的靜態方法。這個方法裏面的this指向的是B,而不是B的實例。

注意,使用super的時候,必須顯式指定是做爲函數、仍是做爲對象使用,不然會報錯。

1 class A {}
2 
3 class B extends A {
4   constructor() {
5     super();
6     console.log(super); // 報錯
7   }
8 }

上面代碼中,console.log(super)當中的super,沒法看出是做爲函數使用,仍是做爲對象使用,因此 JavaScript 引擎解析代碼的時候就會報錯。這時,若是能清晰地代表super的數據類型,就不會報錯。

class A {}

class B extends A {
  constructor() {
    super();
    console.log(super.valueOf() instanceof B); // true
  }
}

let b = new B();

上面代碼中,super.valueOf()代表super是一個對象,所以就不會報錯。同時,因爲super使得this指向B的實例,因此super.valueOf()返回的是一個B的實例。

最後,因爲對象老是繼承其餘對象的,因此能夠在任意一個對象中,使用super關鍵字。

1 var obj = {
2   toString() {
3     return "MyObject: " + super.toString();
4   }
5 };
6 
7 obj.toString(); // MyObject: [object Object]

四、 類的 prototype 屬性 和 __proto__屬性

大多數瀏覽器的 ES5 實現之中,每個對象都有__proto__屬性,指向對應的構造函數的prototype屬性。Class 做爲構造函數的語法糖,同時有prototype屬性和__proto__屬性,所以同時存在兩條繼承鏈。

(1)子類的__proto__屬性,表示構造函數的繼承,老是指向父類。

(2)子類prototype屬性的__proto__屬性,表示方法的繼承,老是指向父類的prototype屬性。

class A {
}

class B extends A {
}

B.__proto__ === A // true
B.prototype.__proto__ === A.prototype // true

上面代碼中,子類B__proto__屬性指向父類A,子類Bprototype屬性的__proto__屬性指向父類Aprototype屬性。

這樣的結果是由於,類的繼承是按照下面的模式實現的。

 1 class A {
 2 }
 3 
 4 class B {
 5 }
 6 
 7 // B 的實例繼承 A 的實例
 8 Object.setPrototypeOf(B.prototype, A.prototype);
 9 
10 // B 繼承 A 的靜態屬性
11 Object.setPrototypeOf(B, A);
12 
13 const b = new B();

《對象的擴展》給出過Object.setPrototypeOf方法的實現。

1 Object.setPrototypeOf = function (obj, proto) {
2   obj.__proto__ = proto;
3   return obj;
4 }

所以,就獲得了上面的結果。

1 Object.setPrototypeOf(B.prototype, A.prototype);
2 // 等同於
3 B.prototype.__proto__ = A.prototype;
4 
5 Object.setPrototypeOf(B, A);
6 // 等同於
7 B.__proto__ = A;

這兩條繼承鏈,能夠這樣理解:做爲一個對象,子類(B)的原型(__proto__屬性)是父類(A);

做爲一個構造函數,子類(B)的原型對象(prototype屬性)是父類的原型對象(prototype屬性)的實例。

1 Object.create(A.prototype);
2 // 等同於
3 B.prototype.__proto__ = A.prototype;

**  extends的繼承目標

extends關鍵字後面能夠跟多種類型的值。

1 class B extends A {
2 }

上面代碼的A,只要是一個有prototype屬性的函數,就能被B繼承。因爲函數都有prototype屬性(除了Function.prototype函數),所以A能夠是任意函數。

下面,討論三種特殊狀況。

  第一種特殊狀況,子類繼承Object類:

1 class A extends Object {
2 }
3 
4 A.__proto__ === Object // true
5 A.prototype.__proto__ === Object.prototype // true

這種狀況下,A其實就是構造函數Object的複製,A的實例就是Object的實例。

  第二種特殊狀況,不存在任何繼承:

1 class A {
2 }
3 
4 A.__proto__ === Function.prototype // true
5 A.prototype.__proto__ === Object.prototype // true

這種狀況下,A做爲一個基類(即不存在任何繼承),就是一個普通函數,因此直接繼承Function.prototype

可是,A調用後返回一個空對象(即Object實例),因此A.prototype.__proto__指向構造函數(Object)的prototype屬性。

  第三種特殊狀況,子類繼承null:

1 class A extends null {
2 }
3 
4 A.__proto__ === Function.prototype // true
5 A.prototype.__proto__ === undefined // true

這種狀況與第二種狀況很是像。A也是一個普通函數,因此直接繼承Function.prototype。可是,A調用後返回的對象不繼承任何方法,因此它的__proto__指向Function.prototype,即實質上執行了下面的代碼。

1 class C extends null {
2   constructor() { return Object.create(null); }
3 }

** 實例的 __proto__ 屬性

子類實例的__proto__屬性的__proto__屬性,指向父類實例的__proto__屬性。也就是說,子類的原型的原型,是父類的原型。

1 var p1 = new Point(2, 3);
2 var p2 = new ColorPoint(2, 3, 'red');
3 
4 p2.__proto__ === p1.__proto__ // false
5 p2.__proto__.__proto__ === p1.__proto__ // true

上面代碼中,ColorPoint繼承了Point,致使前者原型的原型是後者的原型。

所以,經過子類實例的__proto__.__proto__屬性,能夠修改父類實例的行爲。 

1 p2.__proto__.__proto__.printName = function () {
2   console.log('Ha');
3 };
4 
5 p1.printName() // "Ha"

上面代碼在ColorPoint的實例p2上向Point類添加方法,結果影響到了Point的實例p1


 

五、原生構造函數的繼承

原生構造函數是指語言內置的構造函數,一般用來生成數據結構。ECMAScript 的原生構造函數大體有下面這些。

  • Boolean()
  • Number()
  • String()
  • Array()
  • Date()
  • Function()
  • RegExp()
  • Error()
  • Object()

之前,這些原生構造函數是沒法繼承的,好比,不能本身定義一個Array的子類。

 1 function MyArray() {
 2   Array.apply(this, arguments);
 3 }
 4 
 5 MyArray.prototype = Object.create(Array.prototype, {
 6   constructor: {
 7     value: MyArray,
 8     writable: true,
 9     configurable: true,
10     enumerable: true
11   }
12 });

上面代碼定義了一個繼承 Array 的MyArray類。可是,這個類的行爲與Array徹底不一致。

1 var colors = new MyArray();
2 colors[0] = "red";
3 colors.length  // 0
4 
5 colors.length = 0;
6 colors[0]  // "red"

之因此會發生這種狀況,是由於子類沒法得到原生構造函數的內部屬性,經過Array.apply()或者分配給原型對象都不行。原生構造函數會忽略apply方法傳入的this,也就是說,原生構造函數的this沒法綁定,致使拿不到內部屬性。

ES5 是先新建子類的實例對象this,再將父類的屬性添加到子類上,因爲父類的內部屬性沒法獲取,致使沒法繼承原生的構造函數。好比,Array構造函數有一個內部屬性[[DefineOwnProperty]],用來定義新屬性時,更新length屬性,這個內部屬性沒法在子類獲取,致使子類的length屬性行爲不正常。

下面的例子中,咱們想讓一個普通對象繼承Error對象。

 1 var e = {};
 2 
 3 Object.getOwnPropertyNames(Error.call(e))
 4 // [ 'stack' ]
 5 
 6 Object.getOwnPropertyNames(e)
 7 // []var e = {};
 8 
 9 Object.getOwnPropertyNames(Error.call(e))
10 // [ 'stack' ]
11 
12 Object.getOwnPropertyNames(e)
13 // []

上面代碼中,咱們想經過Error.call(e)這種寫法,讓普通對象e具備Error對象的實例屬性。可是,Error.call()徹底忽略傳入的第一個參數,而是返回一個新對象,e自己沒有任何變化。這證實了Error.call(e)這種寫法,沒法繼承原生構造函數。

ES6 容許繼承原生構造函數定義子類,由於 ES6 是先新建父類的實例對象this,而後再用子類的構造函數修飾this,使得父類的全部行爲均可以繼承。下面是一個繼承Array的例子。

 1 class MyArray extends Array {
 2   constructor(...args) {
 3     super(...args);
 4   }
 5 }
 6 
 7 var arr = new MyArray();
 8 arr[0] = 12;
 9 arr.length // 1
10 
11 arr.length = 0;
12 arr[0] // undefined

上面代碼定義了一個MyArray類,繼承了Array構造函數,所以就能夠從MyArray生成數組的實例。這意味着,ES6 能夠自定義原生數據結構(好比ArrayString等)的子類,這是 ES5 沒法作到的。

上面這個例子也說明,extends關鍵字不只能夠用來繼承類,還能夠用來繼承原生的構造函數。所以能夠在原生數據結構的基礎上,定義本身的數據結構。下面就是定義了一個帶版本功能的數組。

 1 class VersionedArray extends Array {
 2   constructor() {
 3     super();
 4     this.history = [[]];
 5   }
 6   commit() {
 7     this.history.push(this.slice());
 8   }
 9   revert() {
10     this.splice(0, this.length, ...this.history[this.history.length - 1]);
11   }
12 }
13 
14 var x = new VersionedArray();
15 
16 x.push(1);
17 x.push(2);
18 x // [1, 2]
19 x.history // [[]]
20 
21 x.commit();
22 x.history // [[], [1, 2]]
23 
24 x.push(3);
25 x // [1, 2, 3]
26 x.history // [[], [1, 2]]
27 
28 x.revert();
29 x // [1, 2]
View Code

上面代碼中,VersionedArray會經過commit方法,將本身的當前狀態生成一個版本快照,存入history屬性。revert方法用來將數組重置爲最新一次保存的版本。除此以外,VersionedArray依然是一個普通數組,全部原生的數組方法均可以在它上面調用。

下面是一個自定義Error子類的例子,能夠用來定製報錯時的行爲。

 1 class ExtendableError extends Error {
 2   constructor(message) {
 3     super();
 4     this.message = message;
 5     this.stack = (new Error()).stack;
 6     this.name = this.constructor.name;
 7   }
 8 }
 9 
10 class MyError extends ExtendableError {
11   constructor(m) {
12     super(m);
13   }
14 }
15 
16 var myerror = new MyError('ll');
17 myerror.message // "ll"
18 myerror instanceof Error // true
19 myerror.name // "MyError"
20 myerror.stack
21 // Error
22 //     at MyError.ExtendableError
23 //     ...
View Code

注意,繼承Object的子類,有一個行爲差別

1 class NewObj extends Object{
2   constructor(){
3     super(...arguments);
4   }
5 }
6 var o = new NewObj({attr: true});
7 o.attr === true  // false

上面代碼中,NewObj繼承了Object,可是沒法經過super方法向父類Object傳參。這是由於 ES6 改變了Object構造函數的行爲,一旦發現Object方法不是經過new Object()這種形式調用,ES6 規定Object構造函數會忽略參數。

 


 

六、 Mixin 模式的實現

Mixin 指的是多個對象合成一個新的對象,新對象具備各個組成成員的接口。它的最簡單實現以下。

1 const a = {
2   a: 'a'
3 };
4 const b = {
5   b: 'b'
6 };
7 const c = {...a, ...b}; // {a: 'a', b: 'b'}

上面代碼中,c對象是a對象和b對象的合成,具備二者的接口。

下面是一個更完備的實現,將多個類的接口「混入」(mix in)另外一個類。

 1 function mix(...mixins) {
 2   class Mix {}
 3 
 4   for (let mixin of mixins) {
 5     copyProperties(Mix, mixin); // 拷貝實例屬性
 6     copyProperties(Mix.prototype, mixin.prototype); // 拷貝原型屬性
 7   }
 8 
 9   return Mix;
10 }
11 
12 function copyProperties(target, source) {
13   for (let key of Reflect.ownKeys(source)) {
14     if ( key !== "constructor"
15       && key !== "prototype"
16       && key !== "name"
17     ) {
18       let desc = Object.getOwnPropertyDescriptor(source, key);
19       Object.defineProperty(target, key, desc);
20     }
21   }
22 }

上面代碼的mix函數,能夠將多個對象合成爲一個類。使用的時候,只要繼承這個類便可。

class DistributedEdit extends mix(Loggable, Serializable) {
  // ...
}
相關文章
相關標籤/搜索