2011-05-10 27 views
0

我試圖將從Facebook API調用接收到的數據存儲到類屬性中。將從匿名函數接收的數據保存在類對象中

我的構造函數:

function Foo() { 
    this.bar = { 
     likes: 0 
    }; 
} 

方法來更新對象:

Foo.prototype.update = function() { 
    FB.api('/me/likes', function (response) { 
     // this.bar['likes'] is out of the scope 
    }); 

} 


var foo = new Foo(); 
foo.update(); 

這是可能的,或者我應該只是儘量做到同步調用呢? 我不確定Facebook的API是否支持它。

感謝

+0

您正在將數據存儲在對象的屬性中,而不是類中。 JavaScript是一種典型的語言,並沒有像古典語言那樣的類。在JavaScript中,函數是第一類對象,「Foo」是一個對象。用構造函數的名字大寫第一個字符只是一個約定,它並不賦予'Foo'任何特殊的含義。 – 2011-06-07 09:20:48

回答

2
Foo.prototype.update = function() 
{ 
    var self = this; 
    FB.api('/me/likes', function (response){ 
     self.bar["likes"] = response; 
    }); 

} 

如果緩存this作爲一個局部變量,那麼你可以參考它的回調函數內。

或者,您可以使用ES5綁定命令或jQuery替代品$.proxy。或下劃線替代_.bind

FB.api('/me/likes', (function (response){ 
    this.bar["likes"] = response; 
}).bind(this)); 

FB.api('/me/likes', $.proxy(function (response){ 
    this.bar["likes"] = response; 
}, this)); 

FB.api('/me/likes', _.bind(function (response){ 
    this.bar["likes"] = response; 
}, this)); 

所有這些都將確保在您的函數的this值是你希望它是什麼。 (請注意,.bind是ES5,並在舊瀏覽器中打破)。

如果你有jQuery,你可以使用$ .proxy。如果您不想包含jQuery,請改爲包含下劃線,因爲它更小。

+0

正是我在找的東西。謝謝! – Shirak 2011-05-10 00:47:04

相關問題