箭頭函數有幾個使用注意點。javascript
(1)函數體內的this
對象,就是定義時所在的對象,而不是使用時所在的對象。java
(2)不能夠看成構造函數,也就是說,不可使用new
命令,不然會拋出一個錯誤。app
(3)不可使用arguments
對象,該對象在函數體內不存在。若是要用,能夠用Rest參數代替。函數
(4)不可使用yield
命令,所以箭頭函數不能用做Generator函數。this
上面四點中,第一點尤爲值得注意。this
對象的指向是可變的,可是在箭頭函數中,它是固定的。spa
function foo() { setTimeout(() => { console.log('id:', this.id); }, 100); } var id = 21; foo.call({ id: 42 }); // id: 42
上面代碼中,setTimeout
的參數是一個箭頭函數,這個箭頭函數的定義生效是在foo
函數生成時,而它的真正執行要等到100毫秒後。若是是普通函數,執行時this
應該指向全局對象window
,這時應該輸出21
。可是,箭頭函數致使this
老是指向函數定義生效時所在的對象(本例是{id: 42}
),因此輸出的是42
。code
箭頭函數可讓setTimeout
裏面的this
,綁定定義時所在的做用域,而不是指向運行時所在的做用域。下面是另外一個例子。對象
function Timer() { this.s1 = 0; this.s2 = 0; // 箭頭函數 setInterval(() => this.s1++, 1000); // 普通函數 setInterval(function () { this.s2++; }, 1000); } var timer = new Timer(); setTimeout(() => console.log('s1: ', timer.s1), 3100); setTimeout(() => console.log('s2: ', timer.s2), 3100); // s1: 3 // s2: 0
上面代碼中,Timer
函數內部設置了兩個定時器,分別使用了箭頭函數和普通函數。前者的this
綁定定義時所在的做用域(即Timer
函數),後者的this
指向運行時所在的做用域(即全局對象)。因此,3100毫秒以後,timer.s1
被更新了3次,而timer.s2
一次都沒更新。token
箭頭函數可讓this
指向固定化,這種特性頗有利於封裝回調函數。下面是一個例子,DOM事件的回調函數封裝在一個對象裏面。事件
var handler = { id: '123456', init: function() { document.addEventListener('click', event => this.doSomething(event.type), false); }, doSomething: function(type) { console.log('Handling ' + type + ' for ' + this.id); } };
上面代碼的init
方法中,使用了箭頭函數,這致使這個箭頭函數裏面的this
,老是指向handler
對象。不然,回調函數運行時,this.doSomething
這一行會報錯,由於此時this
指向document
對象。
this
指向的固定化,並非由於箭頭函數內部有綁定this
的機制,實際緣由是箭頭函數根本沒有本身的this
,致使內部的this
就是外層代碼塊的this
。正是由於它沒有this
,因此也就不能用做構造函數。
因此,箭頭函數轉成ES5的代碼以下。
// ES6 function foo() { setTimeout(() => { console.log('id:', this.id); }, 100); } // ES5 function foo() { var _this = this; setTimeout(function () { console.log('id:', _this.id); }, 100); }
上面代碼中,轉換後的ES5版本清楚地說明了,箭頭函數裏面根本沒有本身的this
,而是引用外層的this
。
請問下面的代碼之中有幾個this
?
function foo() { return () => { return () => { return () => { console.log('id:', this.id); }; }; }; } var f = foo.call({id: 1}); var t1 = f.call({id: 2})()(); // id: 1 var t2 = f().call({id: 3})(); // id: 1 var t3 = f()().call({id: 4}); // id: 1
上面代碼之中,只有一個this
,就是函數foo
的this
,因此t1
、t2
、t3
都輸出一樣的結果。由於全部的內層函數都是箭頭函數,都沒有本身的this
,它們的this
其實都是最外層foo
函數的this
。
除了this
,如下三個變量在箭頭函數之中也是不存在的,指向外層函數的對應變量:arguments
、super
、new.target
。
function foo() { setTimeout(() => { console.log('args:', arguments); }, 100); } foo(2, 4, 6, 8) // args: [2, 4, 6, 8]
上面代碼中,箭頭函數內部的變量arguments
,實際上是函數foo
的arguments
變量。
另外,因爲箭頭函數沒有本身的this
,因此固然也就不能用call()
、apply()
、bind()
這些方法去改變this
的指向。
(function() { return [ (() => this.x).bind({ x: 'inner' })() ]; }).call({ x: 'outer' }); // ['outer']
上面代碼中,箭頭函數沒有本身的this
,因此bind
方法無效,內部的this
指向外部的this
。
長期以來,JavaScript語言的this
對象一直是一個使人頭痛的問題,在對象方法中使用this
,必須很是當心。箭頭函數」綁定」this
,很大程度上解決了這個困擾。