箭頭函數與普通function的區別

1. 箭頭函數沒有自己的this,它裏面的this是繼承所屬上下文中的this,而且使用call與apply都無法改變 let obj = { name: 'obj' } function fn1() { console.log(this); } fn1.call(obj); let fn2() => { console.log(this); } fn2.call(obj); 2. 普通函數的參數是arguments,而箭頭函數是arg let arr = [1,2,3] ~function(){ console.log(arguments); } (arr); //輸出 [1,2,3] let a = (...arg) => { console.log(arg); } a(arr) //輸出[1,2,3] 3. 語法上比普通函數更加簡潔 function fn1(x) { return function(y) { return x + y; } } let fn1 = x => y => x + y; 4. 箭頭函數不能使用new生成構造函數,因爲箭頭函數沒有prototype,而construct在prototype裏面。 function Fn1() { this.x = 100; } let f1 = new Fn1; let Fn2 = () => { this.x = 200; } let f2 = new Fn2; //輸出 Fn2 is not a constructor
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章