這個恐怕是ES6最最常用的一個新特性了,用它來寫function比原來的寫法要簡潔清晰很多:
function(i){ return i + 1; } //ES5(i) => i + 1 //ES6簡直是簡單的不像話對吧… 如果方程比較復雜,則需要用{}把代碼包起來:
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運行上面的代碼會報錯,這是因為setTimeout中的this指向的是全局對象。所以為了讓它能夠正確的運行,傳統(tǒng)的解決方法有兩種:
第一種是將this傳給self,再用self來指代this
says(say){ var self = this; setTimeout(function(){ console.log(self.type + ' says ' + say) }, 1000)第二種方法是用bind(this),即
says(say){ setTimeout(function(){ console.log(self.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當我們使用箭頭函數(shù)時,函數(shù)體內的this對象,就是定義時所在的對象,而不是使用時所在的對象。 并不是因為箭頭函數(shù)內部有綁定this的機制,實際原因是箭頭函數(shù)根本沒有自己的this,它的this是繼承外面的,因此內部的this就是外層代碼塊的this。
新聞熱點
疑難解答