开发者

Proper Context Usage of this keyword within a method callback

I am trying to开发者_Python百科 get the correct context of "this" when calling a method inside a prototype. It appears that the this keyword is referencing the callback method and not the prototype object that that $.getJSON is being used on. How do I correctly call the object's Timer within the getJSON callback?

function Stocks()
{
    var Timer;
}

Stocks.prototype.GetQuote = function ()
{

    var requestURL = ""; //Some URL filled

    $.getJSON(requestURL, function(result)
    {
         //Error Line
         clearTimeout(this.Timer); //This is the wrong context
    });
    this.Timer = setTimeout(this.QueryRequest.bind(this, ''), 1000);
}
Stocks.prototype.QueryRequest= function ()
{
    console.log('Requested');
    this.Timer = setTimeout(this.QueryRequest.bind(this, ''), 1000);
}


You can bind the function, which will force the function to be run with a certain this value:

$.getJSON(requestURL, (function(result) {

     // this 'this' is the same 'this' as before and after
     // the JSON call due to .bind

     this.Timer.clearTimeout();


// create a new function with a fixed 'this' value. To be specific, set it to
// the current 'this' value so that the inner and outer 'this' value are equal

}).bind(this));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜