Javascript object properties are displayed in the console, but undefined?

I find it difficult to understand how to access object properties in Javascript. I have a function that returns an object, and I can see this object and all its properties when it registers on the console in Safari, but I cannot get property values ​​for other functions. For example, an attempt to notify about one of the properties returns "undefined".

Function that generates the object


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;
}

Trying to use this function in another script


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

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

+3
source share
2 answers

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);
  });
}

:

function loadProfile() {
  facebook.getProfile(function (profile) {
    alert(profile.name);
  });
}

, ou , , . .

+5

" " , , . .

, , :

var myObj = new Object();

myObj['key1'] = 'val1';
myObj['key2'] = 'val2';
myObj['key3 '] = 'val3';  //the key contains spaces here
myObj['key4 '] = 'val4';  // the key contains spaces here

, console.log(myObj), :

Object { key1="val1", key2="val2", key3 ="val3",  key4 ="val4"}

:

alert(myObj.key1); //Ok: val1  
alert(myObj.key2); //Ok: val2  

alert(myObj.key3); //undefined  
alert(myObj.key4); //undefined  

alert(myObj['key3']; //undefined  
alert(myObj['key4']; //undefined  

, , , -, , , console log , .

0

Source: https://habr.com/ru/post/1756231/


All Articles