I’m trying to get my head around jQuery and JavaScript objects and functions and grasp how this works and where it points to.
Please can someone explain why this works.
Cat.prototype.meowLater = function() {
var self = this;
window.setTimeout(
function() {
self.meow();
}
, 1000);
}
The bit I’m interested in and confused by is why the variable self can actually be accessed in the anonymous function that’s called by the timer. I thought that because self is declared in another function that it would be local and only accessible to that function.
Here,
Since, the
setTimeoutis inner function ofCat.prototype.meowLater,selfavailable tosetTimeout.Also,
we are not using
this.meow()here, becausethisrefers to current object , thus towindowinsetTimeoutfunction.