在ES6的所有新特性中,箭頭函數(Arrow Fucntion)算是我用的最頻繁的特性之一了。
它是函數
那什麼是箭頭函數呢?首先,它得有“函數”的功能。我們平時定義一個函數,大緻是這種樣子的:
function greeting(name) {
return "Hello," + name;
}
我們可以使用箭頭函數來定義一個與它大緻等價的函數:
const greeting = (name) => {
return "Hello," + name;
}
更進一步,這個箭頭函數還可以簡化,在箭頭後面隻使用一個表達式:
const greeting = (name) => "Hello," + name;
我們還可以在使用匿名函數的場景使用箭頭函數,比如:
[1, 2, 3].map((item) => item * item);
//結果:[1, 4, 9]
它沒有自己的this綁定
我們來看一個我們經常會遇到的問題:
var person = {
_name: "Kevin",
intro: function () {
console.log(this._name); // Kevin
var getMyIntro = function () {
console.log(this._name); // undefined
return "My name is " + this._name;
};
return getMyIntro();
}
};
person.intro(); //My name is undefined
在這段代碼中,我們期望的結果是:My name is Kevin,但是它的結果卻是:My name is undefined。在一個對象的成員函數中的内嵌函數,它的this對象并不是指向成員函數所指向的this對象(也就是這個例子中的person對象),而是指向目前執行上下文的頂層對象(在浏覽器中運作的話,就是Window對象)。
在ES6之前,我們怎麼來解決這個問題呢?我們可以像如下代碼一樣,在成員函數中定義一個變量,把成員函數的this緩存下來,然後在内嵌函數中使用成員函數中的這個變量,這樣就達到成員函數和内嵌函數中拿到的資料都是一樣的:
var person = {
_name: "Kevin",
intro: function () {
var that = this; //緩存this
console.log(that._name); // Kevin
var getMyIntro = function () {
console.log(that._name); // Kevin
return "My name is " + that._name;
};
return getMyIntro();
}
};
person.intro(); //My name is Kevin
在ES6中,我們也可以通過箭頭函數來輕松解決這個問題:
var person = {
_name: "Kevin",
intro: function () {
console.log(this._name); // Kevin
var getMyIntro = () => {
console.log(this._name); // Kevin
return "My name is " + this._name;
};
return getMyIntro();
}
};
person.intro(); //My name is Kevin
可以看到,我們将内嵌函數getMyIntro定義成了一個箭頭函數,這樣的話,箭頭函數中的this是和目前上下文中的this是一緻的了。