Class 能夠經過extends
關鍵字實現繼承,這比 ES5 的經過修改原型鏈prototype實現繼承,要清晰和方便不少。數組
class Point {
}
class ColorPoint extends Point {
}
上面代碼定義了一個ColorPoint
類,該類經過extends
關鍵字,繼承了Point
類的全部屬性和方法。可是因爲沒有部署任何代碼,因此這兩個類徹底同樣,等於複製了一個Point
類。下面,咱們在ColorPoint
內部加上代碼。瀏覽器
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
對象,必須先經過父類的構造函數完成塑造,獲得與父類一樣的實例屬性和方法,而後再對其進行加工,加上子類本身的實例屬性和方法。若是不調用super
方法,子類就得不到this
對象,Java中也是會在new子類對象是調用父類的構造方法。app
說白了就是先經過父類的構造方法super拿到一個複製的父類對象,再在這個對象上添加子類本身的屬性和方法,從而實現繼承,若是沒有這個父類對象,繼承也就沒法進行。函數
class Point { /* ... */ } class ColorPoint extends Point { constructor() { } } let cp = new ColorPoint(); // ReferenceError
上面代碼中,ColorPoint
繼承了父類Point
,可是它的構造函數沒有調用super
方法,致使新建實例時報錯。this
ES5 的繼承,實質是先創造子類的實例對象this
,而後再將父類的方法添加到this
上面(Parent.apply(this)
)。spa
ES6 的繼承機制徹底不一樣,實質是先將父類實例對象的屬性和方法,加到this
上面(因此必須先調用super
方法),而後再用子類的構造函數修改this
。prototype
若是子類沒有定義constructor
方法,這個方法會被默認添加,代碼以下。也就是說,無論有沒有顯式定義,任何一個子類都有constructor
方法。code
class ColorPoint extends Point { } // 等同於 class ColorPoint extends Point { constructor(...args) { super(...args); } }
另外一個須要注意的地方是,在子類的構造函數中,只有調用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
同時是ColorPoint
和Point
兩個類的實例,這與 ES5 的行爲徹底一致。
最後,父類的靜態方法,也會被子類繼承。
class A { static hello() { console.log('hello world'); } } class B extends A { } B.hello() // hello world
上面代碼中,hello()
是A
類的靜態方法,B
繼承A
,也繼承了A
的靜態方法。
Object.getPrototypeOf
方法能夠用來從子類上獲取父類。
Object.getPrototypeOf(ColorPoint) === Point // true
所以,可使用這個方法判斷,一個類是否繼承了另外一個類。
super
這個關鍵字,既能夠看成函數使用,也能夠看成對象使用。在這兩種狀況下,它的用法徹底不一樣。
第一種狀況,super
做爲函數調用時,表明父類的構造函數。ES6 要求,子類的構造函數必須執行一次super
函數。
class A {}
class B extends A {
constructor() {
super();
}
}
上面代碼中,子類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()
只能用在子類的構造函數之中,用在其餘地方就會報錯。
class A {} class B extends A { m() { super(); // 報錯 } }
上面代碼中,super()
用在B
類的m
方法之中,就會形成句法錯誤。
第二種狀況,super
做爲對象時,在普通方法中,指向父類的原型對象;在靜態方法中,指向父類。
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 2
上面代碼中,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
的時候,必須顯式指定是做爲函數、仍是做爲對象使用,不然會報錯。
class A {} class B extends A { constructor() { super(); console.log(super); // 報錯 } }
上面代碼中,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
關鍵字。
var obj = { toString() { return "MyObject: " + super.toString(); } }; obj.toString(); // MyObject: [object Object]
大多數瀏覽器的 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
,子類B
的prototype
屬性的__proto__
屬性指向父類A
的prototype
屬性。
這樣的結果是由於,類的繼承是按照下面的模式實現的。
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
方法的實現。
Object.setPrototypeOf = function (obj, proto) { obj.__proto__ = proto; return obj; }
所以,就獲得了上面的結果。
Object.setPrototypeOf(B.prototype, A.prototype); // 等同於 B.prototype.__proto__ = A.prototype; Object.setPrototypeOf(B, A); // 等同於 B.__proto__ = A;
這兩條繼承鏈,能夠這樣理解:
做爲一個對象,子類(B
)的原型(__proto__
屬性)是父類(A
);
做爲一個構造函數,子類(B
)的原型對象(prototype
屬性)是父類的原型對象(prototype
屬性)的實例。
Object.create(A.prototype); // 等同於 B.prototype.__proto__ = A.prototype;
extends
關鍵字後面能夠跟多種類型的值。
class B extends A {
}
上面代碼的A
,只要是一個有prototype
屬性的函數,就能被B
繼承。因爲函數都有prototype
屬性(除了Function.prototype
函數),所以A
能夠是任意函數。
下面,討論兩種狀況。第一種,子類繼承Object
類。
class A extends Object { } A.__proto__ === Object // true A.prototype.__proto__ === Object.prototype // true
這種狀況下,A
其實就是構造函數Object
的複製,A
的實例就是Object
的實例。
第二種狀況,不存在任何繼承。
class A { } A.__proto__ === Function.prototype // true A.prototype.__proto__ === Object.prototype // true
這種狀況下,A
做爲一個基類(即不存在任何繼承),就是一個普通函數,因此直接繼承Function.prototype
。可是,A
調用後返回一個空對象(即Object
實例),因此A.prototype.__proto__
指向構造函數(Object
)的prototype
屬性。
子類實例的__proto__
屬性的__proto__
屬性,指向父類實例的__proto__
屬性(😂😱)。也就是說,子類的原型的原型,是父類的原型。神奇的__proto__。。。。。
var p1 = new Point(2, 3); var p2 = new ColorPoint(2, 3, 'red'); p2.__proto__ === p1.__proto__ // false p2.__proto__.__proto__ === p1.__proto__ // true
上面代碼中,ColorPoint
繼承了Point
,致使前者原型的原型是後者的原型。
所以,經過子類實例的__proto__.__proto__
屬性,能夠修改父類實例的行爲。
p2.__proto__.__proto__.printName = function () { console.log('Ha'); }; p1.printName() // "Ha"
上面代碼在ColorPoint
的實例p2
上向Point
類添加方法,結果影響到了Point
的實例p1
。
原生構造函數是指語言內置的構造函數,一般用來生成數據結構。ECMAScript 的原生構造函數大體有下面這些。
之前,這些原生構造函數是沒法繼承的,好比,不能本身定義一個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
徹底不一致。
var colors = new MyArray(); colors[0] = "red"; colors.length // 0 colors.length = 0; colors[0] // "red"
之因此會發生這種狀況,是由於子類沒法得到原生構造函數的內部屬性,經過Array.apply()
或者分配給原型對象都不行。原生構造函數會忽略apply
方法傳入的this
,也就是說,原生構造函數的this
沒法綁定,致使拿不到內部屬性。
ES5 是先新建子類的實例對象this
,再將父類的屬性添加到子類上,因爲父類的內部屬性沒法獲取,致使沒法繼承原生的構造函數。好比,Array
構造函數有一個內部屬性[[DefineOwnProperty]]
,用來定義新屬性時,更新length
屬性,這個內部屬性沒法在子類獲取,致使子類的length
屬性行爲不正常。
下面的例子中,咱們想讓一個普通對象繼承Error
對象。
var e = {}; Object.getOwnPropertyNames(Error.call(e)) // [ 'stack' ] Object.getOwnPropertyNames(e) // []
上面代碼中,咱們想經過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 能夠自定義原生數據結構(好比Array
、String
等)的子類,這是 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]
上面代碼中,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 // ...
注意,繼承Object
的子類,有一個行爲差別。
class NewObj extends Object{ constructor(){ super(...arguments); } } var o = new NewObj({attr: true}); o.attr === true // false
上面代碼中,NewObj
繼承了Object
,可是沒法經過super
方法向父類Object
傳參。這是由於 ES6 改變了Object
構造函數的行爲,一旦發現Object
方法不是經過new Object()
這種形式調用,ES6 規定Object
構造函數會忽略參數。
Mixin 指的是多個對象合成一個新的對象,新對象具備各個組成成員的接口。它的最簡單實現以下。
const a = { a: 'a' }; const b = { b: 'b' }; const c = {...a, ...b}; // {a: 'a', b: 'b'}
上面代碼中,c
對象是a
對象和b
對象的合成,具備二者的接口。
下面是一個更完備的實現,將多個類的接口「混入」(mix in)另外一個類。
1 function mix(...mixins) { 2 class Mix { 3 constructor() { 4 for (let mixin of mixins) { 5 copyProperties(this, new mixin()); // 拷貝實例屬性 6 } 7 } 8 } 9 10 for (let mixin of mixins) { 11 copyProperties(Mix, mixin); // 拷貝靜態屬性 12 copyProperties(Mix.prototype, mixin.prototype); // 拷貝原型屬性 13 } 14 15 return Mix; 16 } 17 18 function copyProperties(target, source) { 19 for (let key of Reflect.ownKeys(source)) { 20 if ( key !== 'constructor' 21 && key !== 'prototype' 22 && key !== 'name' 23 ) { 24 let desc = Object.getOwnPropertyDescriptor(source, key); 25 Object.defineProperty(target, key, desc); 26 } 27 } 28 }
上面代碼的mix
函數,能夠將多個對象合成爲一個類。使用的時候,只要繼承這個類便可。
class DistributedEdit extends mix(Loggable, Serializable) { // ... }
從而實現多繼承。