箭頭函數可使咱們的代碼更加簡潔,以下:數組
var sum = (a,b) => a+b;
JavaScript 充滿了咱們須要編寫在其餘地方執行的小函數的狀況。app
例如:函數
……還有更多。this
JavaScript 的精髓在於建立一個函數並將其傳遞到某個地方。 在這樣的函數中,咱們一般不想離開當前上下文。這就是箭頭函數的主戰場啦。spa
箭頭函數沒有 this 。若是訪問 this ,則會從外 部獲取。code
const group = { title: "Our Group", students: ["John", "Pete", "Alice"], showList() { this.students.forEach((student) => console.log(`${this.title}:${student}`)); }, }; group.showList();
如何使用普通函數則會出現錯誤,緣由以下:blog
this指向錯誤,由於函數調用的上下文並不是是group繼承
⚠ 不能對箭頭函數進行 new 操做 不具備 this 天然也就意味着另外一個限制:箭頭函數不能用做構造器(constructor)。不能用 new 調用它們。教程
—《現代JavaScript教程》ip
箭頭函數沒有 「arguments」
當咱們須要使用當前的 this 和 arguments 轉發一個調用時,這對裝飾器(decorators)來講 很是有用
function defer(f,ms) { return function () { setTimeout(()=>f.apply(this,arguments),ms); } } function sayHi(who) { console.log(`Hello ${who}`); } const sayHiDeferred = defer(sayHi,2000); sayHiDeferred('Peng');
如何使用普通函數的話,則須要以下這樣:
function defer (f,ms) { return function(...args) { const ctx = this; setTimeout(function() { return f.apply(ctx,args); },ms); } }
箭頭函數總結: