As JavaScript coding procedures and configuration designs have turned out to be progressively modern throughout the years, there's been a relating increment in the multiplication of self-referencing degrees inside callbacks and terminations, which are a genuinely basic wellspring of "this/that perplexity".
Consider this illustration code piece:
Game.prototype.restart = function () {
this.clearLocalStorage();
this.timer = setTimeout(function() {
this.clearBoard(); // what is "this"?
}, 0);
};
Executing the above code brings about the accompanying mistake:Uncaught TypeError: undefined is not a function
Why?It's about setting. The reason you get the above blunder is on the grounds that, when you summon setTimeout(), you are really conjuring window.setTimeout(). Subsequently, the mysterious capacity being passed to setTimeout() is being characterized with regards to the window protest, which has no clearBoard() technique.
A customary, old-program agreeable arrangement is to just spare your reference to this in a variable that would then be able to be acquired by the conclusion; e.g.:
Game.prototype.restart = function () {
this.clearLocalStorage();
var self = this; // save reference to 'this', while it's still this!
this.timer = setTimeout(function(){
self.clearBoard(); // oh OK, I do know who 'self' is!
}, 0);
};
Then again, in more up to date programs, you can utilize the predicament() strategy to go in the best possible reference:
Game.prototype.restart = function () {
this.clearLocalStorage();
this.timer = setTimeout(this.reset.bind(this), 0); // bind to 'this'
};
Game.prototype.reset = function(){
this.clearBoard(); // ahhh, back in the context of the right 'this'!
};
0 comments:
Post a Comment