2017-04-25 61 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

你應該總是正確地與一個分號結束您的匿名函數的結尾。使用分號結束正常的非匿名函數不是必需的。

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

Oooooooooh,這是真氣。我只是花了所有的時間錯過了分號。儘管如此,感謝您的及時迴應。 – Frank

相關問題