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'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.
-
what do you hope to achieve here? what's
AnotherFunction
called for? by convention, constructors start with Capitalized letters. isAnotherFunction
another constructor? or just a function to be called? – Joseph Commented Mar 17, 2012 at 23:21 -
It's very plex, that's why I didn't copy my actual code in here. Basically, 'for real', it's a function called ClearCharacter that clears an ASCII character off the page by calling another object's Draw() function, which overwrites MyObj's Draw() function, which is another function I didn't include here because it was irrelevant but that draws an ASCII character on the page via setting the innerHTML value of a <p> element. Like I said, plex and very irrelevant. So yeah,
AnotherFunction
is just a function to be called. =) – Elliot Bonneville Commented Mar 17, 2012 at 23:23
1 Answer
Reset to default 7I 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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745141780a4613463.html
评论列表(0条)