首先我們先看一段代碼,這是一個實現倒數功能的類「Countdown」及其實例化的過程:
function Countdown(seconds) { this._seconds = seconds;}Countdown.prototype._step = function() { console.log(this._seconds); if (this._seconds > 0) { this._seconds -= 1; } else { clearInterval(this._timer); }};Countdown.prototype.start = function() { this._step(); this._timer = setInterval(function() { this._step(); }, 1000);};new Countdown(10).start();運行這段代碼時,將會出現異常「this._step is not a function」。
這是Javascript中頗受詬病的「this錯亂」問題:setInterval重復執行的函數中的this已經跟外部的this不一致了。
要解決這個問題,有三個方法。
閉包
新增一個變量指向期望的this,然后將該變量放到閉包中:
Countdown.prototype.start = function() { var self = this; this._step(); this._timer = setInterval(function() { self._step(); }, 1000);};bind函數
ES5給函數類型新增的「bind」方法可以改變函數(實際上是返回了一個新的函數)的「this」:
Countdown.prototype.start = function() { this._step(); this._timer = setInterval(function() { this._step(); }.bind(this), 1000);};箭頭函數
這正是本文要重點介紹的解決方案。箭頭函數是ES6中新增的語言特性,表面上看,它只是使匿名函數的編碼更加簡短,但實際上它還隱藏了一個非常重要的細節――箭頭函數會捕獲其所在上下文的this作為自己的this。也就是說,箭頭函數內部與其外部的this是保持一致的。
所以,解決方案如下:
Countdown.prototype.start = function() { this._step(); this._timer = setInterval(() => { this._step(); }, 1000);};這無疑使this的處理更加方便了。然而,對各位Javascript Coder而言,判斷this指向時的情況可就又多了一種了。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
新聞熱點
疑難解答