recursively calling a function within a class definition

Discussion in 'Javascript' started by jman, Aug 13, 2007.

  1. jman

    jman Guest

    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.
     
    jman, Aug 13, 2007
    #1
    1. Advertising

  2. On Aug 13, 11:50 am, jman <> wrote:
    > 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
     
    David Golightly, Aug 14, 2007
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Andreas Lagemann
    Replies:
    8
    Views:
    512
    Mike Wahler
    Jan 10, 2005
  2. tiwy
    Replies:
    0
    Views:
    457
  3. Jianli Shen
    Replies:
    1
    Views:
    614
    Victor Bazarov
    Mar 13, 2005
  4. Tomi Lindberg

    Class definition within function

    Tomi Lindberg, Aug 2, 2006, in forum: Python
    Replies:
    9
    Views:
    425
    Rick Zantow
    Aug 2, 2006
  5. csx
    Replies:
    0
    Views:
    79
Loading...

Share This Page