深入理解Javascript箭頭函數中的this,深入理解javascript

來源:互聯網
上載者:User

深入理解Javascript箭頭函數中的this,深入理解javascript

首先我們先看一段代碼,這是一個實現倒數功能的類「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指向時的情況可就又多了一種了。

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的協助,如果有疑問大家可以留言交流。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.