[Javascript] Javascript Objects and Scope

Ryan Cannon ryan at ryancannon.com
Fri Nov 18 13:30:57 CST 2005


Hi folks,

I'm just starting with Javascript objects, and I'm having variable  
scope issue that I can't seem to resolve. The following works:

function customClass() {
     this.myFunc=function() {
         // do something
     }
}
window.onload=function() {
     var foo=new customClass();
     foo.test=function() {
         interval=setInterval(function() {
             if (test)
                 foo.increment();
             else clearInterval(interval);
         }, 400);
     }
     foo.test();
}

Trying to move the interval inside the object, however, fails:

function customClass() {
     this.myFunc=function() {
         // do something
     }
     this.test=function() {
         interval=setInterval(function() {
             if (test)
                 this.increment();
             else clearInterval(interval);
         },400);
     }
}
window.onload=function() {
     var foo=new customClass();
     foo.test();
}

I have a feeling this is a scope problem, because javascript doesn't  
throw an error. Any ideas?

-- 
Ryan Cannon

Wordslinger, Webwright
http://RyanCannon.com






More information about the Javascript mailing list