ES6新特性之箭頭函式與function的區別
1.寫法不同
// function的寫法 function fn(a, b){ return a+b; }
// 箭頭函式的寫法 let foo = (a, b) =>{ return a + b }
2.this的指向不同
在function中,this指向的是呼叫該函式的物件;
//使用function定義的函式 function foo(){ console.log(this); } var obj = { aa: foo }; foo(); //Window obj.aa() //obj { aa: foo }
而在箭頭函式中,this永遠指向定義函式的環境。
//使用箭頭函式定義函式 var foo = () => { console.log(this) }; var obj = { aa:foo }; foo(); //Window obj.aa(); //Window
function Timer() { this.s1 = 0; this.s2 = 0; // 箭頭函式 setInterval(() => { this.s1++; console.log(this); }, 1000); // 這裡的this指向timer // 普通函式 setInterval(function () { console.log(this); this.s2++; // 這裡的this指向window的this }, 1000); } var timer = new Timer(); setTimeout(() => console.log('s1: ', timer.s1), 3100); setTimeout(() => console.log('s2: ', timer.s2), 3100); // s1: 3 // s2: 0
3.箭頭函式不可以當建構函式
//使用function方法定義建構函式 function Person(name, age){ this.name = name; this.age = age; } var lenhart =new Person(lenhart, 25); console.log(lenhart); //{name: 'lenhart', age: 25}
//嘗試使用箭頭函式 var Person = (name, age) =>{ this.name = name; this.age = age; }; var lenhart = new Person('lenhart', 25); //Uncaught TypeError: Person is not a constructor
另外,由於箭頭函式沒有自己的this,所以當然也就不能用call()、apply()、bind()這些方法去改變this的指向。
4.變數提升
function存在變數提升,可以定義在呼叫語句後;
foo(); //123 function foo(){ console.log('123'); }
箭頭函式以字面量形式賦值,是不存在變數提升的;
arrowFn(); //Uncaught TypeError: arrowFn is not a function var arrowFn = () => { console.log('456'); };
console.log(f1); //function f1() {} console.log(f2); //undefined function f1() {} var f2 = function() {}