ES6入門(一)30分鐘掌握

  1. let const
    let 塊級作用域
    const 常量
    作用:當(dāng)改變變量值的時候回報錯,不讓更改。
    可以當(dāng)我們引用第三方類庫的時候,可以防止我們重名。
  2. class extends super
    結(jié)局了很多es5的難點(diǎn),繼承。。。。。
  3. 箭頭函數(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對象,就是定義時所在的對象,而不是使用時所在的對象。
并不是因?yàn)榧^函數(shù)內(nèi)部有綁定this的機(jī)制,實(shí)際原因是箭頭函數(shù)根本沒有自己的this,它的this是繼承外面的,因此內(nèi)部的this就是外層代碼塊的this。

  1. template string
    。。。
  2. destructuring解構(gòu)
    ES6允許按照一定模式,從數(shù)組和對象中提取值,對變量進(jìn)行賦值,這被稱為解構(gòu)(Destructuring)。
  3. rest default
    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)容

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