2017-04-25 15 views
0

私は、次のコードを実行しているから、奇妙な結果を経験しています:自己呼び出しの無名関数の直上に置かれたときに関数が変数に代入されるのはなぜですか?

var saySomethingElse, v; 

// This function will not run when the nameless function runs, even if v and saySomethingElse are commented out. 
function saySomething() { 

    alert("something"); 

} 

// When v is uncommented, this function will run when the nameless function below runs.. 
saySomethingElse = function() { 

    alert("something else"); 

} 

//v = "by uncommenting me, saySomethingElse will no longer be called."; 

(function() { 

    if (v) { 

    alert("Now things are working normally.") 

    } 

    alert("This alert doesn't happen if v is commented out."); 

})(); 

このコードが実行されると、一番下の無名関数ではなく、独自のコンテンツのsaySomethingElseを呼び出しますが、vがコメント解除された場合に予想されるように、すべての作品:saySomethingElseは実行されず、無名関数は独自のコンテンツを実行します。私はこれがおそらく正常な動作だと思っていますが、私は説明を探しています。誰がなぜこれが起こっているのか知っていますか?

がフィドルをチェックアウト:working example

+0

コンソールを使用する方法を学ぶのがよいでしょう –

答えて

1

をあなたは、あなたが常に適切にセミコロンを使用して匿名関数を終了する必要があり、あなたの無名関数の最後にsaySomethingElse

をセミコロンを追加する必要があります。セミコロンを使用して通常の非匿名のfunction fooBar() {}機能を終了する必要はありません。

var saySomethingElse, v; 
 

 
// This function will not run when the nameless function runs, even if v and saySomethingElse are commented out. 
 
function saySomething() { 
 

 
    alert("something"); 
 

 
} // <-- Semi-colon not necessary. 
 

 
// When v is uncommented, this function will run when the nameless function below runs.. 
 
saySomethingElse = function() { 
 

 
    alert("something else"); 
 

 
}; // <-- Semi-colon recommended to prevent errors like you're getting. 
 

 
//v = "by uncommenting me, saySomethingElse will no longer be called."; 
 

 
(function() { 
 

 
    if (v) { 
 

 
    alert("Now things are working normally.") 
 

 
    } 
 

 
    alert("This alert doesn't happen if v is commented out."); 
 

 
})();

あなたは今saySomethingElseが正常終了時に終了したことを期待するようになりましたコード機能します。

JavaScriptでは、すべてのステートメントの最後にセミコロンを使用することが予想されるためです。匿名関数定義は、他の変数定義と同様に、ステートメントです。

+0

、それは怒っています。私はちょうどセミコロンを忘れてしまったので、その時間を過ごしました。しかし、迅速な対応に感謝します。 – Frank

関連する問題