Gustavo
Gustavo

Reputation: 1683

JavaScript setInterval scope issue: an alternative to bind

I just correct a scope problem in my JavaScript Class with bind method that put the function called by setInterval in the right scope. But it seams bind has come early (1.8.4 I think) and I'm worry with browser compatibility.

Is there another older alternative? Should I forget about old browsers?

Example:

function MyClass(SomeText){
  this.text = SomeText;
}

MyClass.prototype.test = function(){
  console.log("The text: "+this.text);
}

MyClass.prototype.initialize = function(){
  setInterval(this.test.bind(this), 1000);
}

var Test = new MyClass("my thoughts");
Test.initialize();

Upvotes: 1

Views: 2364

Answers (1)

bfavaretto
bfavaretto

Reputation: 71908

The alternative is a good ol' closure:

MyClass.prototype.initialize = function(){
    var myClassInstance = this;
    setInterval(function() {
        myClassInstance.test()
    }, 1000);
}

Isn't exactly pretty, but does work cross-browser.

If you want something similar to bind, you can create your own function to do that, or use the polyfill found at MDN. If you're using jQuery, you can use $.proxy, that does the same thing.

Upvotes: 5

Related Questions