SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    setTimeout() scoping issue

    Code JavaScript:
    function Person(name) {
        this.name = name;
     
        this.SayName = function() {
            alert(this.name);
        }
     
        this.SayNameLater = function() {
            setTimeout('this.SayName()', 2000);
        }
    }
     
    person1 = new Person('crmalibu');
    person1.SayNameLater();

    I can't get this to work.
    I want setTimeout() to call the the method from the correct object, but it seems that setTimeout() executes in the global scope. How can I make it refer to the correct object, without using a global variable?

    This works, but uses global variables. I won't know what the global variables will be named(and they may not even be global) so I can't use this.
    Code JavaScript:
        this.SayNameLater = function() {
            setTimeout('person1.SayName()', 2000);
        }

  2. #2
    SitePoint Wizard gRoberts's Avatar
    Join Date
    Oct 2004
    Location
    Birtley, UK
    Posts
    2,439
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I do the following...

    Code javascript:
    function Person(name) {
        this.name = name;
        var me = this;
     
        this.SayName = function() {
            alert(this.name);
        }
     
        this.SayNameLater = function() {
            setTimeout(function() {
            me.SayName();
        }, 2000);
        }
    }
     
    person1 = new Person('crmalibu');
    person1.SayNameLater();


  3. #3
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Nice.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •