I’m trying to make a recursive method but it is losing its binding to this. Here is the simplest way to recreate my issue:
var Foo = function() {
return {
foo : 'foo',
bar : function() {
console.log(this.foo);
setTimeout(this.bar, 500);
}
};
}
var foo = new Foo();
foo.bar();
That will only run twice. The first time it will log foo to the console, and the second it will log undefined. Then of course, it won’t run anymore because bar is no longer a property of this since I assume it was reset to the global object.
I tried var that = this in my bar method and referencing that.foo and that.bar but it doesn’t change anything. I also tried var that = this above my return statement and the issue persists.
Expected result:
foo
foo
foo
foo
… and so on
Here is an example http://jsfiddle.net/k2hTJ/ which results in this:
foo
undefined
setTimeoutwill call its function in the current scope, but withthisas the global object.The best way to work around this is to do something like: