箭頭函數相當於匿名函數,並且簡化了函數定義
(x) => x + 1 相當於:
function(x){
return x + 1;
}
箭頭函數有兩種格式
1.只有一條表達式,可以不用寫{..}與return
// 有參數:
(x, y) => x * x + y * y
// 無參數:
() => alert('無參數')
2.多條表達式
x => {
if (x > 0) {
return x * x;
}
else {
return - x * x;
}
}
如果返回值爲對象
// SyntaxError:
x => { foo: x }
因爲和函數體的{ ... }有語法衝突,所以要改爲:
// ok:
x => ({ foo: x })
使用
var a = () => 10;
alert(a()) >>>10
function Test() {
this.num = 100;
this.func = function(){
console.log(this.num); // 100
var that = this;
#以下兩種寫法的結果一樣
#這裏不能爲this.num,它在匿名函數裏,this指向windows
setTimeout(function(){console.log(that.num);}, 500);
setTimeout(() => console.log(this.num), 500)};
}
var obj = new Test();
obj.func();
箭頭函數內部的this
是詞法作用域,由上下文確定,無法通過call與apply進行綁定