I'm having some interesting issues with passing in variables from within an object into setTimeout. At first, I tried putting the function I was calling from setTimeout on my object so that I wouldn't have to pass any variables into it (I was hoping it could access my object by itself). That didn't work, apparently because the function somehow became global when I called it from setTimeout, and no longer had access to my object's variables.
This was my next attempt, but it doesn't work either:
function MyObj() {
this.foo = 10;
this.bar = 20;
this.duration = 1000;
setTimeout(function(){
AnotherFunction(this.foo, this.bar)
}, this.duration);
}
So, how exactly can I pass in a variable into setTimeout from within an object? No, AnotherFunction won't be able to directly access MyObj for various unrelated reasons, so that's out of the question too.
I think the problem is that when your function executes, this is no longer bound to MyObj. You could try
function MyObj() {
var that = this;
this.foo = 10;
this.foo = 20;
this.duration = 1000;
setTimeout(function(){AnotherFunction(that.foo, that.bar)}, this.duration);
}
Or I do have one more idea should that not work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With