Say I have a set of js that looks like this:
function a() {
this.meow = 0;
var go = setTimeout(function() {
this.parent.meow++;
}, 500);
}
var woof = new a();
Why does woof.meow not increment and if I am referencing it wrong then why does this work:
(function() {
this.meow = 'woof';
var go = setTimeout(function() {
alert(this.parent.meow);
},500);
return true;
})();
and even more confusingly then why doesn’t this work:
(function() {
this.meow = 0;
var go = setTimeout(function() {
alert(this.parent.meow++);
},500);
return true;
})();
parenthas no special meaning in JavaScript (although it does on browsers). In your timeout function,thisdoes not refer to yourainstance, it refers to thewindowobject. It happens that thewindowobject has a property calledparent, but that parent probably doesn’t have a property calledmeow. The reasonthisiswindowin your timeout function is that in JavaScript,thisis defined entirely by how functions are called, not where they’re defined. See links below.Since your timeout function is a closure over the context of the call to
new a, you can do this:What that does is set a variable called
selfto the value ofthiswithin the call toa. The timeout function closes overselfand so can useself.meow.The code you’ve quoted doesn’t work (live example), but I suspect you saw something similar to it work because in that code,
thisreferences thewindowobject, and it’s pretty easy to end up calling a function such thatthisreferenceswindow. Someowwold have ended up being a global variable (all properties you put onwindoware globals).More on closures and
this(on my blog):this