Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q790 How can I use 'this' when using a setTimeout?

You are here: irt.org | FAQ | JavaScript | Timeout | Q790 [ previous next ]

The 'this' only has scope at the time, and not later when a timer triggers. The trick is to retain a reference to 'this' by the use of a global variable:

<SCRIPT LANGUAGE="JavaScript"><!--
var myGlobalVar = null

function myMethod1() {
    this.surname = this.fullname.substring(this.fullname.indexOf(' ') + 1,this.fullname.length);

    // the next line works at this currently has scope:
    this.method2();

    // the next line doesn't work as this will not have scope in a second from now
    setTimeout('this.method2()',1000);

    // the following will work as myGlobalVar always has scope within the current page
    myGlobalVar = this;
    setTimeout('myGlobalVar.method2()',1000);
}

function myMethod2() {
    // the next line works at this always has scope:
    alert(this.surname);
}

function ownObject(fullname) {
    this.fullname = fullname;
    this.method1 = myMethod1;
    this.method2 = myMethod2;
}

myObject = new ownObject('Martin Webb');

myObject.method1();
//--></SCRIPT>

©2018 Martin Webb