ES6引入了class(類)的概念。新的class寫法讓對(duì)象原型的寫法更加清晰腮敌、更像面向?qū)ο缶幊痰恼Z法阱当,也更加通俗易懂。
class Animal{
? ? constructor(){
? ? ? ? this.type = 'animal';
? ? }
? ? says(say){
? ? ? ? console.log(this.type + ' says ' + say);?
? ? }
}
let animal = new Animal();
animal.says('hello')? //animal says hello
class Cat extends Animal{
? ? constructor(){
? ? ? ? ? super();
? ? ? ? ? this.type = 'cat'
? ? ? }? ?
}
let cat = new Cat();
cat.says('hello'); //cat says hello
上面的代碼首先用了class定義了一個(gè)“類”糜工,里面有個(gè)constructor方法,就是構(gòu)造函數(shù)弊添,而this關(guān)鍵字則代表實(shí)例對(duì)象。簡(jiǎn)單地說捌木,constructor內(nèi)定義的方法和屬性是實(shí)例對(duì)象自己的油坝,而constructor外定義的方法和屬性則是所有實(shí)例對(duì)象可以共享的。
class之間可以通過 extends關(guān)鍵字實(shí)現(xiàn)繼承刨裆,這比ES5的通過修改原型鏈實(shí)現(xiàn)繼承澈圈,要清晰和方便很多。上面定義了一個(gè)Cat類帆啃,該類通過extends關(guān)鍵字瞬女,繼承了Animal類的所有屬性和方法。
super關(guān)鍵字努潘,它指代父類的實(shí)例(即父類的this對(duì)象)诽偷。子類必須在constructor方法中調(diào)用super方法,否則新建實(shí)例時(shí)會(huì)報(bào)錯(cuò)疯坤。這是因?yàn)樽宇悰]有自己的this對(duì)象报慕,而是繼承父類的this對(duì)象,然后對(duì)其進(jìn)行加工贴膘。如果不調(diào)用super方法卖子,子類就得不到this對(duì)象。
ES6的繼承機(jī)制刑峡,實(shí)質(zhì)是先創(chuàng)造父類的實(shí)例對(duì)象this(所以必須先調(diào)用super方法)洋闽,然后再用子類的構(gòu)造函數(shù)修改this.