ES6

介紹

ECMAScript 6 在接下來(lái)的一段時(shí)間內(nèi)將成為 ECMAScript的一個(gè)標(biāo)準(zhǔn)。這個(gè)標(biāo)準(zhǔn)預(yù)計(jì)在今年的時(shí)候就會(huì)被簽署,不管在Github,還是在很多社區(qū),javascript愛(ài)好者已經(jīng)早已開始擁抱變化,享受ES6 帶來(lái)的美好,這篇文章將介紹ES6的一些新特性。由于ES6 還沒(méi)有很好地被瀏覽器支持,所以這篇文章的ES6代碼將使用 Babel 進(jìn)行編譯。
ECMAScript 6 的新特性

箭頭(Arrow)

=>是function的簡(jiǎn)寫形式,支持expression和 statement 兩種形式。同時(shí)一點(diǎn)很重要的是它擁有詞法作用域的this值,幫你很好的解決this的指向問(wèn)題,這是一個(gè)很酷的方式,可以幫你減少一些代碼的編寫,先來(lái)看看它的語(yǔ)法。

 ([param] [, param]) => {
       statements
  }
  param => expression

類(class)

ES6 引入了class(類),讓javascript的面向?qū)ο缶幊套兊酶尤菀浊逦腿菀桌斫?。類只是基于原型的面向?qū)ο竽J降恼Z(yǔ)法糖。

   class Animal { // 構(gòu)造方法,實(shí)例化的時(shí)候?qū)?huì)被調(diào)用,如果不指定,那么會(huì)有一個(gè)不帶參數(shù)的默認(rèn)構(gòu)造函數(shù).
         constructor(name,color) {
          this.name = name;
         this.color = color;
          }
        // toString 是原型對(duì)象上的屬性
          toString() {
                      console.log('name:' + this.name + ',color:' + this.color);
          }
}

 var animal = new Animal('dog','white');
 animal.toString();

 console.log(animal.hasOwnProperty('name')); //true
 console.log(animal.hasOwnProperty('toString')); // false
 console.log(animal.__proto__.hasOwnProperty('toString')); // true

 class Cat extends Animal {
         constructor(action) {
          // 子類必須要在constructor中指定super 方法,否則在新建實(shí)例的時(shí)候會(huì)報(bào)錯(cuò).
          // 如果沒(méi)有置頂consructor,默認(rèn)帶super方法的constructor將會(huì)被添加、
          super('cat','white');
          this.action = action;
}
 toString() {
        console.log(super.toString());
    }
}

 var cat = new Cat('catch')
 cat.toString();

 // 實(shí)例cat 是 Cat 和 Animal 的實(shí)例,和Es5完全一致。
  console.log(cat instanceof Cat); // true
 console.log(cat instanceof Animal); // true
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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