Javascript: setTimeout/setInterval on Object Instances

2011-03-01

I was trying to use Javascript’s setInterval function, but I needed to call a method on an object, and that isn’t really supported:

function Foo(x) {
    this.x;
    this.bar = function() {
        alert(this.x);
    }
    this.baz = function() {
        setInterval(<b>"this.bar"</b>, 50);
    }
}

I could pretty much guess the above code wouldn’t work, because this in "this.bar" would clearly be something else once the string was evaluated. I was hoping this code would be okay: setInterval(this.bar, 50). It doesn’t use the string, but passes a method reference directly. It does pass the right method, but unlike, say, Python, Javascript still untethers the method from the object, so inside bar this is still in the global scope and doesn’t evaluate to your instance.

I solved the problem by using closures:

function Foo(x) {
    this.x;
    this.bar = function() {
        alert(this.x);
    }
    this.baz = function() {
        <b>var _this = this;</b>
        setInterval(<b>function() {
            _this.bar();
        }</b>, 50);
    }
}

If bar was essentially a private method and not used elsewhere, you could simplify things to this:

function Foo(x) {
    this.x;
    this.baz = function() {
        var _this = this;
        setInterval(function() {
            alert(_this.x);
        }, 50);
    }
}
blog comments powered by Disqus Prev: jQuery-UI Linked Sliders Next: Visual Studio Unit Tests with Resources