recursively calling a function within a class definition

J

jman

i've got an object and i'd like to recursively call a function
within the class definition.

(i've simplified the code )

function myclass()
{
this.loop = function(index)
{
// ..work

setTimeout( "loop(" + (index+1) + ")", 100 );
}
}

does not work.

i've also tried

setTimeout( function() { loop(index+1) }, 100 );

i've also prefixed this. to loop in both cases - and no workee.

i think it's some sort of scope problem.
 
D

David Golightly

i've got an object and i'd like to recursively call a function
within the class definition.

(i've simplified the code )

function myclass()
{
this.loop = function(index)
{
// ..work

setTimeout( "loop(" + (index+1) + ")", 100 );
}

}

does not work.

i've also tried

setTimeout( function() { loop(index+1) }, 100 );

i've also prefixed this. to loop in both cases - and no workee.

i think it's some sort of scope problem.

Indeed. What you're missing here is more basic than recursion - it's
a fundamental lack of understanding of the nature of JavaScript
scope. Unlike C++ or Java, the "this" keyword is not scoped, by
default, to the current object's context - it must always be
explicitly written out, and doesn't always refer to the object you
might think it does (from a classical OOP background). See
http://developer.mozilla.org/en/doc...nce:Operators:Special_Operators:this_Operator

Another problem here is passing a string as an argument to
setTimeout. While it may technically work, it's terribly inefficient
- by using it, you're invoking the JS compiler to run your string as
code. Pass in a function instead, as you do in your second example.

-David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top