正确的上下文在方法回调中使用此关键字

时间:2011-09-26 15:26:03

标签: javascript

我在原型中调用方法时试图获得“this”的正确上下文。似乎this关键字引用了回调方法,而不是正在使用$ .getJSON的原型对象。如何在getJSON回调中正确调用对象的Timer?

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);
}

1 个答案:

答案 0 :(得分:1)

你可以bind该函数,它将强制该函数以某个this值运行:

$.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));