1,class瞭解
在es6之前,js實現繼承都是通過prototype(原型鏈)的方式來實現的,
原型繼承參考 https://blog.csdn.net/weixin_43322208/article/details/89349703
在es6出現之後,可以通過class來實現繼承。
用新的class關鍵字來編寫以往的構造函數,可以這樣寫:
//構造函數寫法
function Student(name) {
this.name = name;
}
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
}
//class寫法
class Student {
constructor(name) {
this.name = name;
}
hello() {
alert('Hello, ' + this.name + '!');
}
}
var xiaoming = new Student('小明');
xiaoming.hello();
class的定義包含了構造函數constructor和定義在原型對象上的函數hello()(注意沒有function關鍵字),這樣就避免了Student.prototype.hello = function () {…}這樣分散的代碼。
2,class繼承
用class定義對象的另一個巨大的好處是繼承更方便了使用extends。創建一個PrimaryStudent 繼承上方的Student構造函數
class PrimaryStudent extends Student {
constructor(name, grade) {
super(name); // 記得用super調用父類的構造方法!
this.grade = grade;
}
myGrade() {
alert('I am at grade ' + this.grade);
}
}
extends則表示原型鏈對象來自Student
ES6引入的class和原有的JavaScript原型繼承有什麼區別呢?實際上它們沒有任何區別,class的作用就是讓JavaScript引擎去實現原來需要我們自己編寫的原型鏈代碼。簡而言之,用class的好處就是極大地簡化了原型鏈代碼。
缺點:
因爲不是所有的主流瀏覽器都支持ES6的class(IE目前都不支持)。如果一定要現在就用上,就需要一個工具把class代碼轉換爲傳統的prototype代碼,可以試試Babel這個工具
參考鏈接:https://www.liaoxuefeng.com/wiki/1022910821149312/1072866346339712