Passing variables from object to setTimeout
I am having interesting problems passing variables from within an object to setTimeout
. First, I tried to put the function I was calling from setTimeout
onto my object so that I didn't have to pass any variables (I was hoping that he could access my object on his own). It didn't work, apparently because the function somehow became global when I called it from setTimeout
, and no longer had access to my object variables.
This was my next try, 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 a variable in setTimeout
from within an object? No, AnotherFunction
he will not be able to directly contact MyObj
for various reasons unrelated to this.
source to share
I think the problem is that when your function is executed, it is this
no longer tied to MyObj
. You may 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 have another idea that shouldn't work.
source to share