Javascript对象属性在控制台中可见,但未定义?

Gar*_*son 3 javascript

我无法弄清楚如何在Javascript中访问对象属性.我有一个返回一个对象的函数,当它在Safari中记录到控制台时我可以看到该对象及其所有属性,但我无法获取其他函数的属性值.例如,尝试提醒其中一个属性返回'undefined'.

生成对象的函数


getProfile : function() {

  FB.api('/me', function(response) {
    facebook.profile.user_id = response.id;
    facebook.profile.name = response.name;
    facebook.profile.firstName = response.first_name;
    facebook.profile.lastName = response.last_name;
    facebook.profile.gender = response.gender;
  });

  FB.api('/me/photos', {limit: 8}, function(response) {
    facebook.profile.numPhotos = response.data.length;
    for (key in response.data) {
      var photoUrl = response.data[key].source;
      eval('facebook.profile.photo' + key + '= photoUrl');
    }
  });

  return facebook.profile;
}
Run Code Online (Sandbox Code Playgroud)

试图在另一个脚本中使用该功能

function loadProfile() {
  var profile = facebook.getProfile();

console.log(profile); alert(profile.name); }

Run Code Online (Sandbox Code Playgroud)

Ser*_*sky 5

函数getProfile调用FB API函数FB.api,它执行异步HTTP请求.在你的loadProfile函数调用中,你调用getProfile,它会立即返回没有填充数据的facebook.profile对象,因为HTTP请求还没有完成.

考虑以下变化:

getProfile : function(fCallback) {
  var bInfo = false,
      bPhotos = false;    

  FB.api('/me', function(response) {
    facebook.profile.user_id = response.id;
    facebook.profile.name = response.name;
    facebook.profile.firstName = response.first_name;
    facebook.profile.lastName = response.last_name;
    facebook.profile.gender = response.gender;

    bInfo = true;
    if (bPhotos)
       fCallback(facebook.profile);
  });

  FB.api('/me/photos', {limit: 8}, function(response) {
    facebook.profile.numPhotos = response.data.length;
    for (key in response.data) {
      var photoUrl = response.data[key].source;
      eval('facebook.profile.photo' + key + '= photoUrl');
    }

    bPhotos = true;
    if (bInfo)
       fCallback(facebook.profile);
  });
}
Run Code Online (Sandbox Code Playgroud)

并按以下方式调用此函数:

function loadProfile() {
  facebook.getProfile(function (profile) {
    alert(profile.name);
  });
}
Run Code Online (Sandbox Code Playgroud)

你可以在控制台中看到字段的原因是因为你在异步调用成功执行后对对象进行了内省.然而,警报调用立即在尚未填充的对象的同一线程中执行.