相對於原先JS中的函數,ES6增加的箭頭函數更加簡潔,應用起來也更加的方便。本篇是關於箭頭函數的部分學習總結,未完結待續。
三大好處
簡明的語法
一個數組,把它變爲原來的二倍以後輸出。
刪掉一個關鍵字,加上一個胖箭頭;
沒有參數加括號,一個參數可選擇;
多個參數逗號分隔,
const numbers = [5,6,13,0,1,18,23];
//原函數
const double = numbers.map(function (number) {
return number * 2;
})
console.log(double);
//輸出結果
//[ 10, 12, 26, 0, 2, 36, 46 ]
//箭頭函數 去掉function, 添加胖箭頭
const double2 = numbers.map((number) => {
return number * 2;
})
console.log(double2);
//輸出結果
//[ 10, 12, 26, 0, 2, 36, 46 ]
//若只有一個參數,小括號可以不寫(選擇)
const double3 = numbers.map(number => {
return number * 2;
})
console.log(double3);
//若有多個參數,則括號必須寫;若沒有參數,()需要保留
const double4 = numbers.map((number,index) => {
return `${index}:${number * 2}`; //模板字符串
})
console.log(double4);
可以隱式返回
顯示返回就是
const double3 = numbers.map(number => {
return number * 2;
//return 返回內容;
})
箭頭函數的隱式返回就是
當你想簡單返回一些東西的時候,如下:去掉return和大括號,把返回內容移到一行,較爲簡潔;
const double3 = numbers.map(number => number * 2);
補充:箭頭函數是匿名函數,若需調用,須賦值給一個變量,如上 double3。匿名函數在遞歸、解除函數綁定的時候很有用。
不綁定this
一個對象,我們原先在函數中是這麼寫的
一個對象,我們原先在函數中是這麼寫的
const Jelly = {
name:'Jelly',
hobbies:['Coding','Sleeping','Reading'],
printHobbies:function () {
this.hobbies.map(function (hobby) {
console.log(`${this.name} loves ${hobby}`);
})
}
}
Jelly.printHobbies();
// undefined loves Coding
// undefined loves Sleeping
// undefined loves Reading
這說明 this.hobbies 的指向是正確的,this.name 的指向是不正確的;
當一個獨立函數執行時,this 是指向window的
如果要正確指向,原先我們的做法會是 設置變量替換
//中心代碼
printHobbies:function () {
var self = this; // 設置變量替換
this.hobbies.map(function (hobby) {
console.log(`${self.name} loves ${hobby}`);
})
}
Jelly.printHobbies();
// Jelly loves Coding
// Jelly loves Sleeping
// Jelly loves Reading
在ES6箭頭函數中,我們這樣寫
//中心代碼
printHobbies:function () {
this.hobbies.map((hobby)=>{
console.log(`${this.name} loves ${hobby}`);
})
}
// Jelly loves Coding
// Jelly loves Sleeping
// Jelly loves Reading
這是因爲箭頭函數中訪問的this實際上是繼承自其父級作用域中的this,箭頭函數本身的this是不存在的,這樣就相當於箭頭函數的this是在聲明的時候就確定了(詞法作用域),this的指向並不會隨方法的調用而改變。