ES6引入關鍵詞class,class的目的就是讓定義類更簡單;
class Student {
constructor(name) {
this.name = name;
}
hello() {
alert('Hello, ' + this.name + '!');
}
}
class的定義包含了構造函數constructor 和 定義在原型對象上的函數hello() 注意沒有 function 關鍵字,這樣就避免了 Student.prototype.hello = function function_name(argument) {}這樣分散的代碼.
var xiaoming = new Student('小明');
xiaoming.hello()
class繼承
用class定義對象的另一個巨大的好處是繼承更方便了。想一想我們從Student派生一個PrimaryStudent需要編寫的代碼量。現在,原型繼承的中間對象,原型對象的構造函數等等都不需要考慮了,直接通過extends來實現:;
class PrimariyStudent extends Student {
constructor(name,grade){
super(name);//記得調用父類的構造方法
this.grade = grade;
}
myGrade(){
alert('I am at grade ' + this.grade);
}
}
注意PrimaryStudent的定義也是class關鍵字實現的,而extends則表示原型鏈對象來自Student。子類的構造函數可能會與父類不太相同,
例如,PrimaryStudent需要name和grade兩個參數,并且需要通過super(name)來調用父類的構造函數,否則父類的name屬性無法正常初始化。
PrimaryStudent已經自動獲得了父類Student的hello方法,我們又在子類中定義了新的myGrade方法。
ES6引入的class和原有的JavaScript原型繼承有什么區別呢?實際上它們沒有任何區別,class的作用就是讓JavaScript引擎去實現原來需要我們自己編寫的原型鏈代碼。簡而言之,用class的好處就是極大地簡化了原型鏈代碼。
不是所有的主流瀏覽器都支持ES6的class。如果一定要現在就用上,就需要一個工具把class代碼轉換為傳統的prototype代碼,可以試試Babel這個工具。