I seem to be running into a bit of an issue regarding this when used in regards to namespaces in JavaScript. Specifically, whenever I call a namespace function via setTimeout or setInterval I seem to no longer be using the correct value of this.
For example, consider the following code:
var myNamespace = {
myVar: 123,
foo: function () {
console.log('Inside foo');
console.log('this.myVar = ' + this.myVar);
console.log('myNamespace.myVar = ' + myNamespace.myVar);
// This works excactly as expected, it prints 123 and 123
this.bar();
// This does not, it prints undefined and 123
setTimeout(this.bar, 250);
},
bar: function () {
console.log('Inside bar');
console.log('this.myVar = ' + this.myVar);
console.log('myNamespace.myVar = ' + myNamespace.myVar);
}
}
myNamespace.foo();
When bar is called directly from foo everything works as I expect it to: it prints 123 and 123.
However, when bar is called from setTimeout, it prints undefined and 123.
It seems that the second way bar is called that the value of this isn't what I expect. I expect it to be myNamespace but it appears to be window.
That leads me to two questions:
- Is there a way to keep the
thisvalue inside ofbaralways pointing tomyNamespaceregardless of where it was called from? - Would it be more appropriate to hard-code
myNamespace.in place ofthis.inside ofbar?