A deep understanding of this in the Javascript arrow function and a deep understanding of javascript
First, let's take a look at the code. This is a Countdown class "Countdown" 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 occurs 「this._step is not a function
」.
This is a much-criticized "this disorder" in Javascript:This in the setInterval repeated execution function is inconsistent with the external one.
There are three methods to solve this problem.
Closure
Add a variable pointing to the expected this and place it in the closure:
Countdown.prototype.start = function() { var self = this; this._step(); this._timer = setInterval(function() { self._step(); }, 1000);};
Bind Functions
ES5 adds the "bind" method to the function type to change the "this" of the function (actually a new function is returned 」:
Countdown.prototype.start = function() { this._step(); this._timer = setInterval(function() { this._step(); }.bind(this), 1000);};
Arrow Function
This is the solution that we will focus on. Arrow function is a new language feature in es6. on the surface, it only makes the encoding of anonymous functions shorter, but in fact it hides a very important detail-the arrow function will capture the context of this as its own this. That is to say, the arrow function is consistent with the external this.
Therefore, the solution is as follows:
Countdown.prototype.start = function() { this._step(); this._timer = setInterval(() => { this._step(); }, 1000);};
This undoubtedly makes this processing more convenient. However, for Javascript Coder, when judging the point of this, there is another situation.
Summary
The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message.