一偷崩、箭頭函數(shù)語(yǔ)法
ES6標(biāo)準(zhǔn)新增了一種新的函數(shù):Arrow Function(箭頭函數(shù))脱吱。
x => x * x
//上面為箭頭函數(shù)寫(xiě)法,相當(dāng)于下面原來(lái)函數(shù)的寫(xiě)法
function (x) {
return x * x;
}
箭頭函數(shù)相當(dāng)于匿名函數(shù)质涛,并且簡(jiǎn)化了函數(shù)定義稠歉。箭頭函數(shù)有兩種格式,一種像上面的汇陆,只包含一個(gè)表達(dá)式怒炸,連{ ... }和return都省略掉了。還有一種可以包含多條語(yǔ)句毡代,這時(shí)候就不能省略{ ... }和return:
x => {
if (x > 0) {
return x * x;
}
else {
return - x * x;
}
}
如果參數(shù)不是一個(gè)阅羹,就需要用括號(hào)()括起來(lái):
// 兩個(gè)參數(shù):
(x, y) => x * x + y * y
// 無(wú)參數(shù):
() => 3.14
// 可變參數(shù):
(x, y, ...rest) => {
var i, sum = x + y;
for (i=0; i<rest.length; i++) {
sum += rest[i];
}
return sum;
}
如果要返回一個(gè)對(duì)象,就要注意教寂,如果是單表達(dá)式捏鱼,這么寫(xiě)的話(huà)會(huì)報(bào)錯(cuò):
x => ({ foo: x })
二、箭頭函數(shù)與普通函數(shù)(function)區(qū)別
1酪耕、寫(xiě)法上的不同
使用ES6箭頭函數(shù)語(yǔ)法定義函數(shù)导梆,將原函數(shù)的“function”關(guān)鍵字和函數(shù)名都刪掉,并使用“=>”連接參數(shù)列表和函數(shù)體迂烁。當(dāng)函數(shù)參數(shù)只有一個(gè)看尼,括號(hào)可以省略;但是沒(méi)有參數(shù)時(shí)婚被,括號(hào)不可以省略狡忙。
function fun(x, y) {
return x + y;
}
(a, b) => {
return a + b
}
//省略寫(xiě)法
a => a
2、普通函數(shù)的參數(shù)是arguments址芯,而箭頭函數(shù)是arg
箭頭函數(shù)不可以使用arguments對(duì)象,該對(duì)象在函數(shù)體內(nèi)不存在。如果要用谷炸,可以用 rest 參數(shù)代替北专。
const test1=(...numbers)=>{
console.log(numbers)
console.log(arguments)
}
const test2=function(){
console.log(arguments)
}
test1(123);//分別輸出 [123] 報(bào)錯(cuò)
test2(123);//分別輸出 Arguments
3、函數(shù)內(nèi)this的指向不同
在箭頭函數(shù)出現(xiàn)之前旬陡,每個(gè)新定義的普通函數(shù)(function)都有他自己的this值拓颓,箭頭函數(shù)沒(méi)有自己的 this,它里面的 this 是繼承所屬上下文中的 this描孟。
由于箭頭函數(shù)沒(méi)有自己的this指針驶睦,通過(guò)call()、apply()方法調(diào)用時(shí)匿醒,第一個(gè)參數(shù)會(huì)被忽略场航。
關(guān)于call()和apply():
JavaScript中的每一個(gè)Function對(duì)象都有一個(gè)apply()方法和一個(gè)call()方法apply調(diào)用一個(gè)對(duì)象的一個(gè)方法,用另一個(gè)對(duì)象替換當(dāng)前對(duì)象廉羔。例如:B.apply(A, arguments)溉痢;即A對(duì)象調(diào)用B對(duì)象的方法。func.apply(thisArg, [argsArray])
call調(diào)用一個(gè)對(duì)象的一個(gè)方法憋他,用另一個(gè)對(duì)象替換當(dāng)前對(duì)象孩饼。例如:B.call(A,args1,args2);即A對(duì)象調(diào)用B對(duì)象的方法竹挡。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