ES6的箭頭函數詳解:
箭頭函數是ES6中新增一個函數表達形式,它是對函數的一種簡化ES6允許使用“箭頭”(=>)定義函數。
Eg:
var f = v => v;
等同於之前
var f = function(v) {
return v;
};
const Even = n => n % 2 == 0;
const Square = n => n * n;
註:
箭頭函數就是省略了function
參數集與函數體之間一定要有一個箭頭=>
對於參數集而言:
零個參數用 () 表示;
一個參數可以省略 ();
多參數不能省略 ();
Eg:
var f = () => 5;
// 等同於
var f = function () { return 5 };
var sum = (num1, num2) => num1 + num2;
// 等同於
var sum = function(num1, num2) {
return num1 + num2;
};
大括號被解釋為代碼塊,所以如果箭頭函數直接返回一個對象,必須在對象外面加上括號。
Eg:
var getTempItem = id => ({ id: id, name: "Temp" });
[1,2,3].map(function (x) {
return x * x;
});
// [1, 4, 9]
[1,2,3].map(x => x * x);
//[1, 4, 9]
不可以使用arguments對象,該對象在函數體內不存在。如果要用,可以用 rest 參數代替。
const numbers = (...nums) => nums;
numbers(1, 2, 3, 4, 5)
// [1,2,3,4,5]
const haha = (head, ...tail) => [head, tail];
haha(1, 2, 3, 4, 5)
[1, Array[4]]
箭頭函數有幾個使用註意點。
(1) 箭頭函數內部沒有constructor方法,也沒有prototype,所以不支持new操作。但是它對this的處理與一般的普通函數不一樣。箭頭函數的 this 始終指向函數定義時的 this,而非執行時。。
function foo() {
setTimeout(() => {
console.log(‘id:‘, this.id);
}, 100);
}
var id = 21;
foo.call({ id: 22 });
// id: 22
setTimeout的參數是一個箭頭函數,這個箭頭函數的定義生效是在foo函數生成時,而它的真正執行要等到100毫秒後。如果是普通函數,執行時this應該指向全局對象window,這時應該輸出21。但是,箭頭函數導致this總是指向函數定義生效時所在的對象(本例是{id: 22}),所以輸出的是22。
var o = {
x : 1,
func : function() { console.log(this.x) },
test : function() {
setTimeout(function() {
console.log(this);
this.func();
}, 100);
}
};
o.test();
//Window {external: Object, chrome: true, document: document, CNT_SELECT: undefined, jQuery17105021754387381239: Object…}
// this.func is not a function(anonymous function)
出現錯誤,因為this的指向從o變為了全局(函數調用中的this都是指向全局的)。
var o = {
x : 1,
func : function() { console.log(this.x) },
test : function() {
var _this = this;
setTimeout(function() {
_this.func();
}, 100);
}
};
o.test();
// 1
先保存的this就行了。
var o = {
x : 1,
func : function() { console.log(this.x) },
test : function() {
setTimeout(() => { this.func() }, 100);
}
};
o.test();
// 1
(2)this是不會改變指向對象的
var x = 1,
o = {
x : 10,
test : () => this.x
};
o.test();
// 1
o.test.call(o);
// 1
ES6的箭頭函數詳解: