簡體   English   中英

我可以將本地var設置為'this'以在匿名回調函數中引用它嗎?

[英]Can I set a local var to 'this' to reference it inside an anonymous callback function?

我想在回調函數中引用'this',但不能保證'this'將引用正確的對象。 創建引用“ this”的局部變量並在匿名函數中使用該變量是否合適?

例:

var MyClass = function (property) {
  this.property = property;
  someAsynchronousFunction(property, function (result) {
    this.otherProperty = result; // 'this' could be wrong
  });
};

問題是,異步函數可以從任意上下文調用提供的回調(這通常在我的控制范圍之外,例如在使用庫時)。

我建議的解決方案是:

var MyClass = function (property) {
  this.property = property;
  var myClass = this;
  someAsynchronousFunction(property, function (result) {
    myClass.otherProperty = result; // references the right 'this'
  });
};

但是我一直在尋找是否還有其他策略,或者該解決方案是否有問題。

您所做的是確保引用正確對象的經典方法, 盡管您應該在本地定義它 ,即:

function(property) {
    var that = this;

    someFunc(function(result) {
        that.property = whatever;
    }
}

或者,在現代瀏覽器中,您可以顯式綁定它:

someFunc(function(result) {
    this.property = whatever;
}.bind(this));

另請參見: bind()

像jQuery這樣的庫支持后一種功能作為更多瀏覽器支持的代理功能,並且可以簡化為這種可重用的功能:

function proxy(fn, ctx)
{
    return function() {
        return fn.apply(ctx, arguments);
    }
}

並使用它:

someFunc(proxy(function(result) {
    this.property = whatever;
}, this));

是的,那很好,但是不要像您一樣使用隱式全局變量,而要使用局部變量:

var myClass = this;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM