2012-11-17 25 views
0

我有一個示例代碼:使用javascript在facebook init上調用函數時出錯?

window.fbAsyncInit = function() { 
    FB.init({appId: appId, status: true, cookie: true, xfbml: true}); 

    this.test(); 
}; 
// Load the SDK Asynchronously 
(function(d){ 
    var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;} 
    js = d.createElement('script'); js.id = id; js.async = true; 
    js.src = "//connect.facebook.net/en_US/all.js"; 
    d.getElementsByTagName('head')[0].appendChild(js); 
}(document)); 
this.test = function() { 
    alert('test'); 
} 

當我呼籲FB init函數test()是結果爲「TypeError: this.test is not a function」,如何解決呢?

+0

@AndrewII改變的JavaScript的拼寫不是整個編輯一個足夠大的變化。請住手。 – tbodt

回答

0

範圍問題,請在調用測試函數時刪除「this」。 「這個」是指fbAsyncInit函數。

新的代碼(未經測試,但應工作):在全球範圍內

window.fbAsyncInit = function() { 
    FB.init({appId: appId, status: true, cookie: true, xfbml: true}); 

    test(); 
}; 
// Load the SDK Asynchronously 
(function(d){ 
    var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;} 
    js = d.createElement('script'); js.id = id; js.async = true; 
    js.src = "//connect.facebook.net/en_US/all.js"; 
    d.getElementsByTagName('head')[0].appendChild(js); 
}(document)); 
function test() { 
    alert('test'); 
} 
+0

error => ReferenceError:測試未定義 –

+0

也刪除「this」。只是把它定義如下: 功能測試(){ 警報(「試驗」); } – luschn

0

this在功能和this是指向不同的對象;你可以使用window代替this它會起作用。

相關問題