开发者

Passing a reference to an object into anonymous function

I need to pass a reference to the current object into an anonymous function. In Mootools it would be something like this:

    this.start = function(){

        this.intervalId = setInterval(function(){

            this.elapsedTime ++;
            this.setTime();

        }.bind(this), 1000);
    }

But I need it to be done using jQuery and such syntax is not supported in jQuery. What can I do? I tried:

    this.start = function(){

        var thisObj = this;
        this.intervalId = setInterval(function(){

            thisObj.elapsedTime ++;
            thisObj.setTime();

        }, 1000);
    }

But it looks like thisObj is simply a new object because s开发者_如何转开发ome of its methods which were assigned values in the init method are now empty.

Please advise :)


Your code should work, thisObj does not reference a new object. It references this. If this code does not work, it means that you are not calling start() correctly and even bind() would not help you here.

So you have to fix your code first, make sure you are calling start() the right way, like myobj.start().

But in any case, jQuery provides the $.proxy method:

this.intervalId = setInterval($.proxy(function(){
    this.elapsedTime ++;
    this.setTime();
}, this), 1000);

which does the same as .bind().


change thisObj to a global so it exists outside of your start function. The way you had it the setInterval function call wouldn't know what thisObj was

var thisObj = null;

this.start = function(){

    thisObj = this;
    this.intervalId = setInterval(function(){

        thisObj.elapsedTime ++;
        thisObj.setTime();

    }, 1000);
}

working example: http://jsfiddle.net/hunter/Swh9U/


And to prove Felix's point, OP's code does work: http://jsfiddle.net/hunter/Swh9U/1/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜