淺談ES5和ES6繼承和區別

最近想在從新學下ES6,因此就把本身學到的,記錄下增強下本身的理解

首先先簡單的聊下ES5和ES6中的繼承函數

1.在es5中的繼承:

function parent(a,b){
    this a = a;
    this b = b;
}
function child(c){
    this c = c
};

  經過子集去繼承父級:this

parent.call(child,1,2)

  而去看call的底層方法可知,繼承的過程是經過prototype屬性es5

child.prototype = new parent(1,2);

  又此可知,ES5繼承的實質是先建立了子類元素child的的實例對象,而後再把父類元素parent的原型對象中的屬性賦值給子類元素child的實例對象裏面,從而實現繼承spa

2.ES6中的繼承

  在傳統JS中,生成對象是經過建立構造函數,而後定義生成對象prototype

function parent(a,b){
    this.a = a;
    this.b = b;
}

  而後經過prototype增長對應所需方法或屬性code

parent.prototype.methods = function(){
    return 'this is test methods';
}
parent.prototype.attr = 'this is test attr‘;

  而ES6中引入了類的概念,也就是class。經過關鍵詞class去定義對象。
  class是個關鍵詞,語言糖,這樣能更清晰的讀懂所建立的對象,
  經過屬性constructor來接收控制方法傳入的參數,若是不寫這個屬性,默認是沒有參數的對象

class parent{
    curstructor(a,b){
        this.a = a;
        this.b = b;
    }
}        

  ES6中的繼承是基於class類之間繼承的。經過關鍵詞extends實現。
  經過super實例化調用父類blog

class parent{
  constructor(a,b){
    this.a = a;
    this.b = b;
  }
  parentMethods(){
    return this.a + this.b
  }
}
class child extends parent{
  constructor(a,b,c){
    super(a,b);
    this.c = c;
  }
  childMethods(){
    return this.c + ',' + super.parentMethods()
  }
}
const point = new child(1,2,3);
alert(point.childMethods());

  上面的代碼,是一套簡單的ES6父子類繼承。
  相信已經看出來了,雖明顯的區別就是在於ES6中,激活父組件的是super方法,而不是新建實例化,也就是說,父類的實例對象是先建立出來的,調用後,再去修改子類的構造函數中的this完善原型對象繼承

總結:

  ES5和ES6繼承最大的區別就是在於:
    1.ES5先建立子類,在實例化父類並添加到子類this中
    2.ES6先建立父類,在實例化子集中經過調用super方法訪問父級後,在經過修改this實現繼承原型

相關文章
相關標籤/搜索