As far as I know only the declaration part of a function expression gets hoisted not the initialization. E.g.:
var myFunction = function myFunction() {console.log('Hello World');};
So "var myFunction;" gets hoisted, but "function myFunction()..." not.
Now to my question, I played a little bit around with the google auth functions:
"use strict";
$(document).ready = (function() {
var clientId = 'MYCLIENTID';
var apiKey = 'MYAPIKEY';
var scopes = 'https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/drive.appfolder https://www.googleapis.com/auth/drive.apps.readonly https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.install https://www.googleapis.com/auth/drive.metadata https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/drive.photos.readonly https://www.googleapis.com/auth/drive.scripts';
$('#init').click(function() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth(false, handleAuthResult), 1);
});
var checkAuth = function checkAuth(imm, callback) {
gapi.auth.authorize({
client_id: clientId,
scope: scopes,
immediate: imm
}, callback);
};
var handleAuthResult = function handleAuthResult(authResult) {
if (authResult) {
gapi.client.load('drive', 'v2', initialize);
} else {
$('#progress').html('Anmeldung fehlgeschlagen');
}
};
// Other code
})();
On line 10 "window.setTimeout(checkAuth..." I call the checkAuth function which is declared below this function call. My assumption was that I get an error saying "...checkAuth is not a function / undefined etc. ...", but instead it worked. Could someone please explain this to me?
That's because when an actual click event on the element is triggered, the value of checkAuth is then available in the scope. The error you expected would happen this way:
checkAuth(false, ...); // the symbol is available, but...
// its value is assigned here
var checkAuth = function checkAuth() {
/* more code */
};
Notice the immediate invocation of checkAuth() before it's assigned in the above snippet.
What is available at the point of invocation is the symbol named checkAuth; its value, though, gets assigned later. Hence the error checkAuth is not a function rather than checkAuth is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With