轉(zhuǎn)換
例子1
var sum = (num1, num2) => num1 + num2;
// 等同于
var sum = function(num1, num2) {
return num1 + num2;
};
箭頭函數(shù)有幾個使用注意點(diǎn)薯酝。
(1)函數(shù)體內(nèi)的this對象,就是定義時所在的對象母截,而不是使用時所在的對象到忽。
(2)不可以當(dāng)作構(gòu)造函數(shù),也就是說清寇,不可以使用new命令喘漏,否則會拋出一個錯誤。
(3)不可以使用arguments對象华烟,該對象在函數(shù)體內(nèi)不存在翩迈。如果要用,可以用 rest 參數(shù)代替盔夜。
(4)不可以使用yield命令负饲,因此箭頭函數(shù)不能用作 Generator 函數(shù)。
上面四點(diǎn)中比吭,第一點(diǎn)尤其值得注意绽族。this對象的指向是可變的,但是在箭頭函數(shù)中衩藤,它是固定的吧慢。
function foo() {
setTimeout(() => {
console.log('id:', this.id);
}, 100);
}
var id = 21;
foo.call({ id: 42 });
例子2
箭頭函數(shù)可以讓setTimeout里面的this,綁定定義時所在的作用域赏表,而不是指向運(yùn)行時所在的作用域检诗。下面是另一個例子。
function Timer() {
this.s1 = 0;
this.s2 = 0;
// 箭頭函數(shù)
setInterval(() => this.s1++, 1000);
// 普通函數(shù)
setInterval(function () {
this.s2++;
}, 1000);
}
var timer = new Timer();
setTimeout(() => console.log('s1: ', timer.s1), 3100);
setTimeout(() => console.log('s2: ', timer.s2), 3100);
// s1: 3
// s2: 0
例子3
箭頭函數(shù)可以讓this指向固定化瓢剿,這種特性很有利于封裝回調(diào)函數(shù)逢慌。下面是一個例子,DOM 事件的回調(diào)函數(shù)封裝在一個對象里面间狂。
var handler = {
id: '123456',
init: function() {
document.addEventListener('click',
event => this.doSomething(event.type), false);
},
doSomething: function(type) {
console.log('Handling ' + type + ' for ' + this.id);
}
};
例子4
嵌套的箭頭函數(shù)
箭頭函數(shù)內(nèi)部攻泼,還可以再使用箭頭函數(shù)。下面是一個 ES5 語法的多重嵌套函數(shù)鉴象。
function insert(value) {
return {into: function (array) {
return {after: function (afterValue) {
array.splice(array.indexOf(afterValue) + 1, 0, value);
return array;
}};
}};
}
insert(2).into([1, 3]).after(1); //[1, 2, 3]
上面這個函數(shù)忙菠,可以使用箭頭函數(shù)改寫。
let insert = (value) => ({into: (array) => ({after: (afterValue) => {
array.splice(array.indexOf(afterValue) + 1, 0, value);
return array;
}})});
insert(2).into([1, 3]).after(1); //[1, 2, 3]
// id: 42