JavaScript ES6新語法

最常用的ES6特性

  • let,
  • const,
  • class,
  • extends,
  • super,
  • arrow functions,
  • template string,
  • destructuring,
  • default,
  • rest arguments

let

letvar的作用相似都是用來聲明變量的,ES5只有全局作用域和函數(shù)作用域,沒有塊級作用域,而let則實際上為JavaScript新增了塊級作用域。用它所聲明的變量,只在let命令所在的代碼塊內(nèi)有效。

場景一:

test(){

    var name = '張三';
    while(true){
      var name = '李四';//李四
      console.log(name);
      break;
    }
    console.log(name);//李四
  }
test(){

    let name = '張三';
    while(true){
      let name = '李四';
      console.log(name);//李四
      break;
    }
    console.log(name);//張三
  }

test(){

    var name = '張三';
    while(true){
      let name = '李四';
      console.log(name);
      break;
    }
    console.log(name);
  }
#兩者輸出一致,由于let離開塊級作用域就失效了,不會對var name的作用域內(nèi)產(chǎn)生影響
test(){

    let name = '張三';
    while(true){
      var name = '李四';
      console.log(name);
      break;
    }
    console.log(name);
  }

#會報重復(fù)定義變量name的錯誤,var name沒有塊級作用域與let name定義沖突

場景二:

另外一個var帶來的不合理場景就是用來計數(shù)的循環(huán)變量泄露為全局變量,看下面的例子:

test(){
    var a = [];
    for (var i = 0; i < 10; i++) {
      a[i] = function () {
        console.log(i);
      };
    }
    a[6]();//10
  }

上面代碼中,變量i是var聲明的,在全局范圍內(nèi)都有效。所以每一次循環(huán),新的i值都會覆蓋舊值,導(dǎo)致最后輸出的是最后一輪的i的值。而使用let則不會出現(xiàn)這個問題。

test(){
    var a = [];
    for (let i = 0; i < 10; i++) {
      a[i] = function () {
        console.log(i);
      };
    }
    a[6]();//6
  }

** const**
const也用來聲明變量,但是聲明的是常量。一旦聲明,常量的值就不能改變。

const PI = Math.PI
PI = 23 //Module build failed: SyntaxError: /es6/app.js: "PI" is read-only

嚴(yán)格模式下當(dāng)我們嘗試去改變用const聲明的常量時,瀏覽器就會報錯。const有一個很好的應(yīng)用場景,就是當(dāng)我們引用第三方庫的時聲明的變量,用const來聲明可以避免未來不小心重命名而導(dǎo)致出現(xiàn)bug:

const monent = require('moment')

class, extends, super

ES6提供了更接近傳統(tǒng)語言的寫法,引入了Class(類)這個概念。新的class寫法讓對象原型的寫法更加清晰、更像面向?qū)ο缶幊痰恼Z法,也更加通俗易懂。

class Animal {
    constructor(){
        this.type = 'animal'
    }
    says(say){
        console.log(this.type + ' says ' + say)
    }
}

let animal = new Animal()
animal.says('hello') //animal says hello

class Cat extends Animal {
    constructor(){
        super()
        this.type = 'cat'
    }
}
let cat = new Cat()
cat.says('hello') //cat says hello

上面代碼首先用class定義了一個“類”,可以看到里面有一個constructor方法,這就是構(gòu)造方法,而this關(guān)鍵字則代表實例對象。簡單地說,constructor內(nèi)定義的方法和屬性是實例對象自己的,而constructor外定義的方法和屬性則是所有實例對象可以共享的。

Class之間可以通過extends關(guān)鍵字實現(xiàn)繼承,這比ES5的通過修改原型鏈實現(xiàn)繼承,要清晰和方便很多。上面定義了一個Cat類,該類通過extends關(guān)鍵字,繼承了Animal類的所有屬性和方法。

super關(guān)鍵字,它指代父類的實例(即父類的this對象)。子類必須在constructor方法中調(diào)用super方法,否則新建實例時會報錯。這是因為子類沒有自己的this對象,而是繼承父類的this對象,然后對其進(jìn)行加工。如果不調(diào)用super方法,子類就得不到this對象。

ES6的繼承機(jī)制,實質(zhì)是先創(chuàng)造父類的實例對象this(所以必須先調(diào)用super方法),然后再用子類的構(gòu)造函數(shù)修改this。

arrow function

這個恐怕是ES6最最常用的一個新特性了,用它來寫function比原來的寫法要簡潔清晰很多:

function(i){ return i + 1; } //ES5
(i) => i + 1 //ES6

簡直是簡單的不像話對吧...
如果方程比較復(fù)雜,則需要用{}把代碼包起來:

function(x, y) { 
    x++;
    y--;
    return x + y;
}
(x, y) => {x++; y--; return x+y}

除了看上去更簡潔以外,arrow function還有一項超級無敵的功能!
長期以來,JavaScript語言的this對象一直是一個令人頭痛的問題,在對象方法中使用this,必須非常小心。例如:

class Animal {
    constructor(){
        this.type = 'animal'
    }
    says(say){
        setTimeout(function(){
            console.log(this.type + ' says ' + say)
        }, 1000)
    }
}

 var animal = new Animal()
 animal.says('hi')  //undefined says hi

運(yùn)行上面的代碼會報錯,這是因為setTimeout中的this指向的是全局對象。所以為了讓它能夠正確的運(yùn)行,傳統(tǒng)的解決方法有兩種:

第一種是將this傳給self,再用self來指代this

   says(say){
       var self = this;
       setTimeout(function(){
           console.log(self.type + ' says ' + say)
       }, 1000)

2.第二種方法是用bind(this),即

   says(say){
       setTimeout(function(){
           console.log(this.type + ' says ' + say)
       }.bind(this), 1000)

但現(xiàn)在我們有了箭頭函數(shù),就不需要這么麻煩了:

class Animal {
    constructor(){
        this.type = 'animal'
    }
    says(say){
        setTimeout( () => {
            console.log(this.type + ' says ' + say)
        }, 1000)
    }
}
 var animal = new Animal()
 animal.says('hi')  //animal says hi

當(dāng)我們使用箭頭函數(shù)時,函數(shù)體內(nèi)的this對象,就是定義時所在的對象,而不是使用時所在的對象。并不是因為箭頭函數(shù)內(nèi)部有綁定this的機(jī)制,實際原因是箭頭函數(shù)根本沒有自己的this,它的this是繼承外面的,因此內(nèi)部的this就是外層代碼塊的this。

template string

模板字符串的使用方法:

test(){

    var person ={
      name:'張三'
    } ;
    //注意是``不是''
    console.log(`Hi,${person.name}`);//Hi,張三
  }

destructuring

ES6允許按照一定模式,從數(shù)組和對象中提取值,對變量進(jìn)行賦值,這被稱為解構(gòu)(Destructuring)。
看下面的例子:

let cat = 'ken'
let dog = 'lili'
let zoo = {cat: cat, dog: dog}
console.log(zoo) //Object {cat: "ken", dog: "lili"}

用ES6完全可以像下面這么寫:
let cat = 'ken'
let dog = 'lili'
let zoo = {cat, dog}
console.log(zoo) //Object {cat: "ken", dog: "lili"}

反過來可以這么寫:

let dog = {type: 'animal', many: 2}
let { type, many} = dog
console.log(type, many) //animal 2

default, rest

default很簡單,意思就是默認(rèn)值。大家可以看下面的例子,調(diào)用animal()
方法時忘了傳參數(shù),傳統(tǒng)的做法就是加上這一句type = type || 'cat'
來指定默認(rèn)值。

function animal(type){ 
  type = type || 'cat' 
  console.log(type)
}
  animal()

如果用ES6我們而已直接這么寫:
function animal(type = 'cat'){ 
  console.log(type)
}
animal()

最后一個rest語法也很簡單,直接看例子:
function animals(...types){ 
  console.log(types)
}
animals('cat', 'dog', 'fish') //["cat", "dog", "fish"]

而如果不用ES6的話,我們則得使用ES5的arguments

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

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

  • class的基本用法 概述 JavaScript語言的傳統(tǒng)方法是通過構(gòu)造函數(shù),定義并生成新對象。下面是一個例子: ...
    呼呼哥閱讀 4,201評論 3 11
  • 轉(zhuǎn)至元數(shù)據(jù)結(jié)尾創(chuàng)建: 董瀟偉,最新修改于: 十二月 23, 2016 轉(zhuǎn)至元數(shù)據(jù)起始第一章:isa和Class一....
    40c0490e5268閱讀 2,043評論 0 9
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,547評論 19 139
  • 三,字符串?dāng)U展 3.1 Unicode表示法 ES6 做出了改進(jìn),只要將碼點(diǎn)放入大括號,就能正確解讀該字符。有了這...
    eastbaby閱讀 1,668評論 0 8
  • { "Unterminated string literal.": "未終止的字符串文本。", "Identifi...
    一粒沙隨風(fēng)飄搖閱讀 11,310評論 0 3

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