ES6學習筆記-function,default, rest

function

es6中function的寫法變得無比簡潔

function(i){return i +1 ;} //es5
(i) => i + 1;//es6

如果比較複雜,就加個{}把代碼包起來

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

除開簡潔,es6的function還有一個巨牛逼的功能,就是他解決了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

運行上面的代碼會報錯,這是因爲setTimeout中的this指向的是全局對象。
所以爲了讓它能夠正確的運行,傳統的解決方法有兩種:
第一種是將this傳給self,再用self來指代this
第二種方法是用bind(this)
但如果我們改用箭頭函數的形式去寫就不用擔心this的指向問題,這是因爲當我們使用箭頭函數時,函數體內的this對象,就是定義時所在的對象,而不是使用時所在的對象。
並不是因爲箭頭函數內部有綁定this的機制,實際原因是箭頭函數根本沒有自己的this,它的this是繼承外面的,因此內部的this就是外層代碼塊的this。

default, rest

default就是默認值的意思,當一個應該傳參的函數沒有傳參,可以指定一個默認值

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"]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章