Stefano Maglione
Stefano Maglione

Reputation: 4160

Javascript variable scope behavior

in my code below I don't understand why in the final console.log variable bearer_token is undefined if I've inizializated it within function __call.

home: function () {
  var bearer_token;
  var cb = new Codebird;
  cb.setConsumerKey("Zox*O8n1u", "zaCTe5oI23bxx***CG87e8hkgZgBeIHV7LKp");
  cb.__call(
    "oauth2_token", {},
    function (reply) {
      var bearer_token = reply.access_token;
    }
  );
  $.ajax({
    url: "http://search.twitter.com/search.json?q=felpone",
    dataType: "jsonp",
    jsonpCallback: "myFunction",
    beforeSend: function (xhr, settings) {
      xhr.setRequestHeader('Authorization', 'Bearer ' + bearer_token);
    }
  });

  function myFunction(r) {
    console.log(r);
  }
  console.log(bearer_token);
},

Upvotes: 1

Views: 64

Answers (2)

Joseph
Joseph

Reputation: 119847

Two possibilities:

function (reply) {
  var bearer_token = reply.access_token;
}

This piece of code assigns reply.access_token to a bearer_token inside that function and not the one outside the function. This means that if that code runs, it doesn't affect the outside bearer_token. To do so, remove var.

Next, I notice that function has an "oauth2_token" string. Is __call an asynchronous call? If so, then that function next to it is the callback. By the time you did console.log(bearer_token), the response might have not yet arrived. To execute code after an asynchronous operation's response returns, place all the code that should run after the response arrives inside the callback.

This should work:

home: function () {

  var cb = new Codebird;
  cb.setConsumerKey("Zox*O8n1u", "zaCTe5oI23bxx***CG87e8hkgZgBeIHV7LKp");

  cb.__call("oauth2_token", {}, function (reply) {

    var bearer_token = reply.access_token;
    console.log(bearer_token);

    $.ajax({
      url: "http://search.twitter.com/search.json?q=felpone",
      dataType: "jsonp",
      beforeSend: function (xhr, settings) {
        xhr.setRequestHeader('Authorization', 'Bearer ' + bearer_token);
      }
    }).done(function (data) {
      console.log(data);
    });

  });
},

Upvotes: 4

Nish
Nish

Reputation: 1736

You have created a new variable bearer_token in __call scope. Remove var.

Upvotes: 0

Related Questions