Forum Moderators: open

Message Too Old, No Replies

Scope errors with a class and setTimeout()

         

mehh

2:49 pm on Jan 4, 2008 (gmt 0)

10+ Year Member



Im useing setTimeout to enter an infinate loop within a class. However I can't think of anyway to do this without causing scope errors. As the actual code is quite large here is an example version:
function timeoutExample(){
return this;
}
timeoutExample.prototype={
f:function(){
alert("Yahar!")
var t=setTimeout("this.f()",50);
}
}
var foo=new timeoutExample();
foo.f();

Thanks in advance

Fotiman

3:43 pm on Jan 4, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



In your example, inside f() 'this' is going to refer to the prototype object (or maybe the window object), not your actual instance of timeoutExample (as you said, this is a scope issue). f() is like a static function... it doesn't really operate on a particular instance because it is defined in the prototype object instead of being defined in the timeoutExample 'class'. So to fix that, you could modify it slightly to take an instance variable as a parameter, and then call that instances' f() method. Like so:


<script type="text/javascript">
function timeoutExample(){
return this;
}
timeoutExample.prototype = {
f : function(te) {
alert("Yahar!");
setTimeout(function(){te.f(te);}, 50);
}
}
var foo=new timeoutExample();
foo.f(foo);
</script>

Note, instead of passing a string as the first parameter to setTimeout, it's better to pass a function reference. In this case, we're passing an anonymous function which calls the f method of the instance of timeoutExample. Scoping problem fixed. :-)
Hope that helps.

mehh

5:06 pm on Jan 4, 2008 (gmt 0)

10+ Year Member



Thanks, I didn't realise you could pass a function to setTimeout