3

私はこのような機能を持っています:

function foo(canvas) {
    canvas.mousedown(function(e) {
        console.log(canvas); //undefined
    });
}

ページの特定の場所でマウスをクリックすると、foo が呼び出されます。

キャンバスが定義されていないのはなぜですか?

4

4 に答える 4

11

デバッガーは、使用されるまでクロージャー内の変数を表示しない場合があります。

a 変数が定義されているが使用されていない次の例を考えてみましょう。

(function() {
  var x = 1;
  $(function () {
    debugger; // debugger stopped here, `x` is `undefined` in Chrome and IE but `1` in Firefox
    console.log("hi");
  }
})();

文字列リテラルの代わりに変数が出力されることを除いて、同じコード:

(function() {
  var x = 1;
  $(function () {
    debugger; // debugger stopped here, all three browsers show `x` as `1`
    console.log(x);
  }
})();
于 2015-03-30T16:46:23.633 に答える
2

問題はこれでした:

function foo(canvas) {
    canvas.mousedown(function(e) {
        console.log(canvas); //undefined
        //...
        for (var i in array) {
            var canvas = array[i].canvas;
            //...
        }
    });
}

正確な理由を調べる時間はありません。私の推測では、コンソールでの出力時に変数が未定義になるように、コンパイラが無名関数の先頭に「var canvas」宣言を配置します。そうでなければ、まだ理解していません。

于 2012-11-11T22:46:05.923 に答える
2

コード例全体を示したら、あなた自身の答えは正しいです。「変数巻き上げ」として知られる Javascript の癖に遭遇しました。コードは次のように解釈されます。

function foo(canvas) {
    canvas.mousedown(function(e) {
        var i, canvas; //variable declarations moved to top of function scope
        console.log(canvas); //undefined
        //...
        for (i in array) {
            canvas = array[i].canvas;
            //...
        }
    });
}

見る:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting

http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

于 2013-12-27T18:42:27.510 に答える
0

チャーリーが言ったことはクロムで正しいことを確認したいだけです. debugger ステートメントを使用する場合、クロージャー内で使用する前に、問題の変数への参照を作成する必要がありました。

于 2015-07-28T08:20:33.793 に答える