一、箭頭函數(shù)語法
ES6標(biāo)準(zhǔn)新增了一種新的函數(shù):Arrow Function(箭頭函數(shù))。
x => x * x
//上面為箭頭函數(shù)寫法,相當(dāng)于下面原來函數(shù)的寫法
function (x) {
return x * x;
}
箭頭函數(shù)相當(dāng)于匿名函數(shù),并且簡化了函數(shù)定義。箭頭函數(shù)有兩種格式,一種像上面的,只包含一個表達(dá)式,連{ ... }和return都省略掉了。還有一種可以包含多條語句,這時候就不能省略{ ... }和return:
x => {
if (x > 0) {
return x * x;
}
else {
return - x * x;
}
}
如果參數(shù)不是一個,就需要用括號()括起來:
// 兩個參數(shù):
(x, y) => x * x + y * y
// 無參數(shù):
() => 3.14
// 可變參數(shù):
(x, y, ...rest) => {
var i, sum = x + y;
for (i=0; i<rest.length; i++) {
sum += rest[i];
}
return sum;
}
如果要返回一個對象,就要注意,如果是單表達(dá)式,這么寫的話會報錯:
x => ({ foo: x })
二、箭頭函數(shù)與普通函數(shù)(function)區(qū)別
1、寫法上的不同
使用ES6箭頭函數(shù)語法定義函數(shù),將原函數(shù)的“function”關(guān)鍵字和函數(shù)名都刪掉,并使用“=>”連接參數(shù)列表和函數(shù)體。當(dāng)函數(shù)參數(shù)只有一個,括號可以省略;但是沒有參數(shù)時,括號不可以省略。
function fun(x, y) {
return x + y;
}
(a, b) => {
return a + b
}
//省略寫法
a => a
2、普通函數(shù)的參數(shù)是arguments,而箭頭函數(shù)是arg
箭頭函數(shù)不可以使用arguments對象,該對象在函數(shù)體內(nèi)不存在。如果要用,可以用 rest 參數(shù)代替。
const test1=(...numbers)=>{
console.log(numbers)
console.log(arguments)
}
const test2=function(){
console.log(arguments)
}
test1(123);//分別輸出 [123] 報錯
test2(123);//分別輸出 Arguments
3、函數(shù)內(nèi)this的指向不同
在箭頭函數(shù)出現(xiàn)之前,每個新定義的普通函數(shù)(function)都有他自己的this值,箭頭函數(shù)沒有自己的 this,它里面的 this 是繼承所屬上下文中的 this。
由于箭頭函數(shù)沒有自己的this指針,通過call()、apply()方法調(diào)用時,第一個參數(shù)會被忽略。
關(guān)于call()和apply():
JavaScript中的每一個Function對象都有一個apply()方法和一個call()方法apply調(diào)用一個對象的一個方法,用另一個對象替換當(dāng)前對象。例如:B.apply(A, arguments);即A對象調(diào)用B對象的方法。func.apply(thisArg, [argsArray])
call調(diào)用一個對象的一個方法,用另一個對象替換當(dāng)前對象。例如:B.call(A,args1,args2);即A對象調(diào)用B對象的方法。func.call(thisArg, arg1, arg2, ...)
//使用function定義的函數(shù)
function foo(){
console.log(this);
}
foo(); //Window
//使用箭頭函數(shù)定義函數(shù)
var foo = () => { console.log(this) };
foo(); //Window
4、function是可以定義構(gòu)造函數(shù)的,而箭頭函數(shù)是不行的
/使用function方法定義構(gòu)造函數(shù)
function Dog(name, color){
this.name = name;
this.color= color;
}
var newDog= new Dog('demon', black);
console.log(newDog); //{name: 'demon', color: black}
//嘗試使用箭頭函數(shù)
var Dog= (name, color) =>{
this.name = name;
this.color= color;
};
var newDog= new Dog('demon', black); //Uncaught TypeError: Dogis not a constructor