Keeping OOP Scope While Using setInterval

Recently I have been working on projects that involve classical inheritence in JavaScript and also use window/document methods which requires me to manage the 'this' binding more closely. I encountered a situation where call/apply would not help, so I came up with a quick strategy that will hopefully help someone else out there.

When trying to run something like:

setInterval("this.myFunc()", 1000);

Try the following instead:

var ptr = this;
setInterval(function() { ptr.myFunc() }, 1000);

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <p> <pre>
  • Syntax highlight code surrounded by the {syntaxhighlighter SPEC}...{/syntaxhighlighter} tags, where SPEC is a Syntaxhighlighter options string or "class="OPTIONS" title="the title".
  • Lines and paragraphs break automatically.
  • E-Mail addresses are hidden with reCAPTCHA Mailhide.

More information about formatting options

Complete this form and then pat yourself on the back.