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

相关问题