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

相关问题