Javascript object properties visible in console, but undefined? -


i'm having trouble figuring out how access object properties in javascript. have function returns object, , can see object , of properties when logged console in safari, can't property values other functions. example trying alert out 1 of properties returns 'undefined'.

the function generates 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;     (key in response.data) {       var photourl = response.data[key].source;       eval('facebook.profile.photo' + key + '= photourl');     }   });    return facebook.profile; } 

trying use function in script

 function loadprofile() {   var profile = facebook.getprofile();

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

the function getprofile invokes fb api function fb.api executes asynchoronous http request. in loadprofile function call call getprofile returns facebook.profile object not populated data yet since http request not finished yet.

consider following change:

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;     (key in response.data) {       var photourl = response.data[key].source;       eval('facebook.profile.photo' + key + '= photourl');     }      bphotos = true;     if (binfo)        fcallback(facebook.profile);   }); } 

and call function following way now:

function loadprofile() {   facebook.getprofile(function (profile) {     alert(profile.name);   }); } 

the reason why ou see fields in console because introspected object after asynch call executed. alert call executed in same thread on not yet populated object.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -