前端JS進階二(ES6-Class語法)

Class和普通構(gòu)造函數(shù)有何區(qū)別

前端會使用ES6中的Class來代替JS中的構(gòu)造函數(shù)

JS 構(gòu)造函數(shù)
  function MathHandle(x,y){  //構(gòu)造函數(shù)
    this.x = x;
    this.y = y;
  }
  MathHandle.prototype.add = function(){ //原型的拓展
    return this.x + this.y;
  };

  var m = new MathHandle(1,2);  //實例化構(gòu)造函數(shù)
  console.log(m.add)
Class 語法
  class MathHandle {
      constructor(x, y) {  //構(gòu)造器
           this.x = x
           this.y = y
      }
      add() {
          return this.x + this.y
      }
  }

  const m = new MathHandle(1, 2)
  console.log(m.add())
語法糖

兩種語法的本質(zhì)是一樣的,只是兩種格式不同。

  class MathHandle{
    //.......
  }
  typeof MathHandle   //'function'
  //class MathHandle的本質(zhì)是function
  MathHandle === MathHandle.prototype.constructor  //true
  m.__proto__ === MathHandle.prototype  //true  實例的隱式原型等于構(gòu)造函數(shù)的顯示原型
繼承 - JS
  function Animal(){
    this.name = name
    this.eat = function(){
      console.log('eat')
    }
  }

  function Dog(){
    this.bark = function(){
      console.log('bark')
    }
  }

Dog.prototype = new Animal()  //綁定原型 實現(xiàn)繼承
var hasiqi = new Dog()
hasiqi.bark()
hasiqi.eat()
繼承 - Class
  class Animal{
    constructor(name){
      this.name = name
    }
    eat(){
      console.log('eat')
    }
  }
  
  class Dog extends Animal{
    constructor(name){
      super(name)  //將name傳到Animal的constructor構(gòu)造器中去
      this.name = name
    }
    say(){
      console.log('say')
    }
  }

  const dog= new Dog('哈士奇')
  dog.say()
  dog.eat()

總結(jié)

  • Class在語法上更加貼近面向?qū)ο蟮膶懛?/li>
  • Class在實現(xiàn)繼承更加易讀、易理解
  • 更易于寫java等后端語言的使用
  • Class本質(zhì)是語法糖,還是使用prototype的繼承方式
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容