In depth understanding of this in Javascript arrow function

  • 2021-07-21 05:46:58
  • OfStack

First of all, let's look at a piece of code, which is a class "Countdown" that implements the reciprocal function and its instantiation process:


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();

When you run this code, an exception will occur. " this._step is not a function ".

This is the "this disorder" problem that has been criticized in Javascript: this in the function repeatedly executed by setInterval is no longer the same as the external this.

There are three ways to solve this problem.

Closure

Add 1 variable to point to the desired this, and then put the variable in the closure:


Countdown.prototype.start = function() {
 var self = this;
 this._step();
 this._timer = setInterval(function() {
  self._step();
 }, 1000);
};

bind function

ES5 adds the "bind" method to the function type to change the "this" of the function (which actually returns a new function):


Countdown.prototype.start = function() {
  this._step();
  this._timer = setInterval(function() {
    this._step();
  }.bind(this), 1000);
};

Arrow function

This is the solution that this article will focus on. Arrow function is a new language feature in ES6. On the surface, it only makes the coding of anonymous functions shorter, but in fact it also hides a very important detail-arrow function will capture this in its context as its own this. That is, the this inside and outside the arrow function is kept 1.

So, the solution is as follows:


Countdown.prototype.start = function() {
  this._step();
  this._timer = setInterval(() => {
    this._step();
  }, 1000);
};

This undoubtedly makes the processing of this more convenient. However, for you Javascript Coder, there is one more way to judge the direction of this.

Summarize

The above is the whole content of this article. I hope the content of this article can bring 1 certain help to everyone's study or work. If you have any questions, you can leave a message for communication.


Related articles: