Lost variable value ( Javascript )

Asked

Viewed 129 times

3

I have this class, but every time I ask, and access the value of fb_firstNameis 'Undefined'. What I’m doing wrong?

inside the set method, setFb_firstName(firstName) the value is correct, but when returning with getFb_firstName() has no value.

  function User(sender) {
        var fb_firstName; 


        FB.api('/' + sender, 'get', {access_token: token.getPage_acess_token()}, function (response) {
            setFb_firstName(response.first_name);
        });
        function setFb_firstName(firstName) {
            fb_firstName = firstName;
        }
        ;

        this.getFb_firstName = function () {
            return fb_firstName;
        };
    }
  • was with this same problem here, I solved mine otherwise because it was something else, but I saw this solution here: (http://www.w3schools.com/js/js_scope.asp), is in English but to simplify, where you have var fb_firstname declare as fb_firstName = '';that should work

  • Hasn’t worked yet

1 answer

2


You need to pass a callback function to run at the end of the request, otherwise you will have problems assigning values asynchronously.

Take an example:

var User = function() {
    var username;
    return {
        init: function(callback) {
            FB.init(... , function(response) {
                username = response. username;
                callback();
            });
        },
        getUsername: function() {
            return username;
        }
    }
};

var user = new User(),
    username;
user.init(function() {
    username = user.getUsername();
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.