2017-04-03 49 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'之前先調用回調函數,打印。 –