functioncountdown (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);};NewCountdown (). Start ();
When you run this code, an exception will appear "this._step is not a function". This is a very popular "Thisdisorder " problem in JavaScript: the This in a function that SetInterval repeatedly executes is inconsistent with the external this. There are three ways to solve this problem.
Closed Package
Add a variable that points to the desired this, and then place the variable in the closure:
function () { varthis; This . _step (); this. _timer = SetInterval (function() { self._step (); );};
Bind function
ES5 the new "bind" method for the function type can change the "this" of the function (which actually returns a new function):
function () { this. _step (); this. _timer = SetInterval (function() { this. _step (); }. Bind (this), +);};
Arrow functions
The arrow function is a new language feature in ES6, which, on the surface, simply makes the encoding of the anonymous function shorter, but in fact it hides a very important detail--the arrow function captures this as its ownthis in the context. In other words, the inside of the arrow function is consistent with this one outside of it. So, here's the solution:
function () { this. _step (); this. _timer = SetInterval (() + = {This. _step () ; );};
The problem of "this confusion in JavaScript