2017-04-03 50 views
0

如何在我致电login()时访问buildLoginUrl()?第一个here没有被打印,我认为这是因为对login()的调用从不返回。在javascript中访问内部功能

main.js:

$(document).ready(function() { 
    // login function to kick off the authorization 
    function login(callback) { 
     console.log("here2"); 
     // builds the login URL for user after clicking login button 
     function buildLoginUrl(scopes) { 
      console.log("here3"); 
      return 'https://accounts.spotify.com/authorize?client_id=' + clientID + 
       '&redirect_uri=' + redirectURI + 
       '&scope=' + scopes + 
       '&response_type=token'; 
     } 

     // other stuff 
    } 
// event listeners 
    $("#login").click(function() { 
     // call the login function, we'll get back the accessToken from it 
     console.log("here1"); 
     login(function(accessToken) { 
      // callback function from login, gives us the accessToken 

      //buildLoginUrl(scopes); 
      var request = getUserData(accessToken); 
      console.log("here"); 
      request.get(options, function(error, response, body) { 
       console.log(body); 
      }); 
      // other stuff 
     }); 
    }); 

控制台:

here1 
here2 
here4 
+1

你不在你的例子中的任何地方调用'buildLoginUrl'。你想在哪里打电话? –

+0

除非将其分配给可访问(例如全局)变量或从函数返回,否则无法从封闭函数外部访问它。你为什么不直接在匿名函数中声明它? – Harald

+0

'buildLoginUrl()'永远不会调用,所以'here3'永远不会显示。 –

回答

1

您传递一个回调登录,但login函数不调用回调。这就是为什么你从来没有看到“这里”

+0

我怎样才能让控制台打印出第一个'here'?'var request'和' 'request.GET中()' – stumped

+1

调用回调的'login'内的任何地方 例如:! 功能登录(回调){回调();} – jas7457

+0

谢谢这个解决它 – stumped

0

第一here不被打印出来,我认为这是因为调用 登陆()永远不会返回。

为了保持它的简单:

// here yo are defining login() 
function login(callback) { 
    callback(); 
} 

// here you are invoking login() 
login(function() { 
    console.log('here'); 
}); 

here不会被打印,因为你从来没有内login()调用的回调;您必须拨打callback(如上所示),以便打印here

+0

阅读这些评论后,我加入'buildLoginUrl(scopes);'到'function login(callback)'末尾,但'here'仍然没有打印,但是这里打印出来的是1-4。 – stumped

+0

你必须在'here'之前先调用回调函数,打印。 –