3

私が知る限り、初期化ではなく、関数式の宣言部分のみが巻き上げられます。例えば:

var myFunction = function myFunction() {console.log('Hello World');};

したがって、「var myFunction;」巻き上げられますが、「関数 myFunction()...」ではありません。

私の質問に、私はグーグル認証機能を少しいじってみました:

"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
})();

10 行目「window.setTimeout(checkAuth...」で、この関数呼び出しの下に宣言されている checkAuth 関数を呼び出します。私の仮定では、「...checkAuth は関数ではありません / 未定義など」というエラーが表示されました。.. .」ですが、代わりにうまくいきました。誰かが私にこれを説明してもらえますか?

4

2 に答える 2

2

これは、要素の実際のクリック イベントがトリガーされると、 のスコープで使用可能になるためです。予想していたエラーは次のように発生します。checkAuth

checkAuth(false, ...); // the symbol is available, but...

// its value is assigned here
var checkAuth = function checkAuth() {
    /* more code */
};

上記のスニペットでは、割り当てられるcheckAuth() にがすぐに呼び出されていることに注意してください。

呼び出しの時点で利用できるのは、という名前のシンボルcheckAuthです。ただし、その値は後で割り当てられます。したがって、エラーcheckAuth is not a functionではなく、checkAuth is undefinedです。

于 2015-11-20T17:45:23.443 に答える