gpt4 book ai didi

javascript - 为什么分配给变量的函数直接放置在自调用匿名函数之上时会执行?

转载 作者:行者123 更新时间:2023-12-03 04:28:30 24 4
gpt4 key购买 nike

运行以下代码时,我遇到了奇怪的结果:

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 不执行,匿名函数执行自己的内容。我认为这可能是正常行为,但我正在寻找解释。有谁知道为什么会发生这种情况?

查看 fiddle :working example

最佳答案

您需要在匿名函数末尾添加一个分号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 中,您应该在每个语句的末尾使用分号。匿名函数定义是语句,就像任何其他变量定义一样。

关于javascript - 为什么分配给变量的函数直接放置在自调用匿名函数之上时会执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43599935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com