一:箭頭函數的格式
a:一種為只有一條語句,可以省略{}和return。
x => x * x;
相當於:
function(x) { return x * x; }
b:一種為多條語句,不可以省略{}和return。
x => { if (x > 0) { return 1; } return 2; }
相當於:
function(x){
if (x > 0) {
return 1;
}
return 2;
}
注意:
a.當無參數時或有多個參數時,需要用括號()括起來。
(x, y)=> x + y;
b.當省略{}和return時,返回了一個對象,對象要用括號()括起來。
x=> ({color:"red"});
二:箭頭函數的this
a.箭頭函數沒有自己的 this,其內部的 this 綁定到它的外圍作用域。對象內部的箭頭函數若有this,則指向對象的外圍作用域。
window.color = "red";
//let 聲明的全局變量不具有全局屬性,即不能用window.訪問
let color = "green"; let obj = { color: "blue",
getColor: () => {
return this.color;//this指向window
}
}; let sayColor = () => { return this.color;//this指向window };
obj.getColor();//red sayColor();//red
b.箭頭函數無法使用 call()或 apply()來改變其運行的作用域。
window.color = "red"; let color = "green"; let obj = { color: "blue" }; let sayColor = () => { return this.color; }; sayColor.apply(obj);//red