2

我有一些變量,我正在設置一個函數。當我可以獲取,設置並提醒uid1accessToken2的功能時,如果我嘗試在功能外提醒它們,它會給出undefined。我如何設置值?爲什麼我的變量在回調函數之外未定義?

下面是代碼:

FB.getLoginStatus(function(response) { 
    if (response.status === 'connected') { 
     var uid1 = response.authResponse.userID; 
     alert(uid1); //works here 
     var accessToken2 = response.authResponse.accessToken; 
     alert(accessToken2); //works here 
    } 
    else if (response.status === 'not_authorized') { } 
    else { } 
}); 

alert(uid1); //does NOT work here 
alert(accessToken2); //does NOT work here 
+0

對於未來的讀者,我建議對這個問題進行編輯,以反映變量是在回調函數中設置的。正如所寫的,它看起來像變量範圍是唯一的問題。變量範圍是這個問題相關的兩個問題之一。 – 2012-02-27 05:25:05

回答

3

您將這些變量聲明在您使用它們的範圍之外。要解決你的代碼,聲明它們的功能之外:

var uid1 = ""; 
var accessToken2 = ""; 
FB.getLoginStatus(function(response) { 
    if (response.status === 'connected') { 
     uid1 = response.authResponse.userID; 
     alert(uid1); 
     accessToken2 = response.authResponse.accessToken; 
     alert(accessToken2); 
    } else if (response.status === 'not_authorized') { 

    } else { 

    } 

    alert(uid1); // Values will be set here. 
    alert(accessToken2); 
}); 
alert(uid1); // Values won't reliably be set here. 
alert(accessToken2); 

更新:正如下面的意見建議,因爲你的getLoginStatus方法是異步的,你可能不會在調用alert()外有值方法。我在回撥中添加了其他警報,以顯示您應該嘗試訪問值的位置。

+0

這不會起作用,因爲在警報運行時uid1的值不會被填入。 – jfriend00 2012-02-27 02:24:49

+0

@ jfriend00值不會被設置,但它修復了'undefined'問題,因爲在變量中將存在。 – 2012-02-27 02:31:18

+0

我需要設置的值 – Autolycus 2012-02-27 02:49:01

-2

因爲JavaScript(連同所有的編程語言不斷)的範圍是什麼?

+2

Snarky答案並沒有真正幫助 – 2012-02-27 02:29:34

1

Javascript中的變量具有函數範圍。這意味着它們只存在於用var關鍵字聲明的函數中,除非它們是全局變量。移動var關鍵字出你的功能,但爲了避免使他們的全球一次像這樣的函數中把它包:

(function(){ 
    var uid1, accessToken2; 
    FB.getLoginStatus(function(response) { 
      if (response.status === 'connected') { 
      uid1 = response.authResponse.userID; 
      alert(uid1); works here 
      accessToken2 = response.authResponse.accessToken; 
      alert(accessToken2); //works here 
      } else if (response.status === 'not_authorized') { 

      } else { 

      } 
     }); 
    alert(uid1); //uid1 declared but not set until callback executes 
    alert(accessToken2); //accessToken2 declared but not set until callback executes 
    // these alerts will likely NOT display the information 
    // they are intended to display because of asynchronous callback 
})(); 

alert(uid1); //uid1 is not declared, so this doesn't work 
alert(accessToken2); //accessToken2 is not declared, so this doesn't work 
+0

這不會起作用,因爲uid1的值在警報運行時不會被填充。 – jfriend00 2012-02-27 02:25:11

+0

@ jfriend00 FB.getLoginStatus是異步的嗎? – Paulpro 2012-02-27 02:28:40

+0

是的,FB.getLoginStatus可以是異步的(有時結果被緩存)。這就是爲什麼它需要回調。如果它不是異步的,他們只會返回結果而不是使用回調。 – jfriend00 2012-02-27 03:15:30

2

看來,如果回調函數之前

執行你想你的代碼
alert(uid1); //does NOT work here 
alert(accessToken2); 

由於FB.getLoginStatus可能是異步的,情況並非如此。它會立即返回並繼續提醒您。這裏的問題不僅僅是可變範圍。問題在於,在執行回調之前,您無法訪問要顯示的信息。您無法通過移動變量聲明來編程。你必須在你的程序設計/網站/任何設計中考慮到這個事實。

+0

+1「這裏的問題不僅僅是可變範圍」 – 2012-02-27 11:02:22

相關問題