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:

{syntaxhighlighter brush: jscript;gutter: false; fontsize: 100; first-line: 1; }setInterval(“this.myFunc()”, 1000);{/syntaxhighlighter}

Try the following instead:

{syntaxhighlighter brush: jscript;gutter: false; fontsize: 100; first-line: 1; }var ptr = this;
setInterval(function() { ptr.myFunc() }, 1000);{/syntaxhighlighter}

Leave a comment

Your email address will not be published.