我遇到從運行下面的代碼一個奇怪的結果:爲什麼將函數分配給直接放在自調用匿名函數之上時執行的變量?
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
這將是你很好學習如何使用控制檯 –