我遇到从运行下面的代码一个奇怪的结果:为什么将函数分配给直接放在自调用匿名函数之上时执行的变量?
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
这将是你很好学习如何使用控制台 –