First, let’s look at a piece of code. This is a class "Countdown" that implements the countdown function and its instantiation process:
function Countdown(seconds) { this._seconds = seconds; } ._step = function() { (this._seconds); if (this._seconds > 0) { this._seconds -= 1; } else { clearInterval(this._timer); } }; = function() { this._step(); this._timer = setInterval(function() { this._step(); }, 1000); }; new Countdown(10).start();
When running this code, an exception will appear "this._step is not a function
」。
This is the "this confusion" problem that has been criticized in Javascript:This in the function repeatedly executed by setInterval is inconsistent with this external one.
There are three ways to solve this problem.
Closure
Add a new variable to point to the expected this, and then put the variable into the closure:
= function() { var self = this; this._step(); this._timer = setInterval(function() { self._step(); }, 1000); };
bind function
The "bind" method added to the function type by ES5 can change the "this" of the function (actually returning a new function):
= function() { this._step(); this._timer = setInterval(function() { this._step(); }.bind(this), 1000); };
Arrow function
This is exactly the solution to be introduced in this article. The arrow function is a new language feature added in ES6. On the surface, it only makes the encoding of anonymous functions shorter, but in fact it also hides a very important detail - the arrow function will capture this in its context as its own. That is, the inside of the arrow function is consistent with this outside it.
So, the solution is as follows:
= function() { this._step(); this._timer = setInterval(() => { this._step(); }, 1000); };
This undoubtedly makes this more convenient to handle. However, for all Javascript Coders, there is another one more situation when judging this pointing.
Summarize
The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate.