Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap

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:

    // the next line doesn't work as this will not have scope in a second from now

    // the following will work as myGlobalVar always has scope within the current page
    myGlobalVar = this;

function myMethod2() {
    // the next line works at this always has scope:

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

myObject = new ownObject('Martin Webb');


©2018 Martin Webb