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

时间:2017-04-25 01:06:25

标签: javascript function scope

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

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

1 个答案:

答案 0 :(得分:1)

您需要在匿名函数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.");

})();
&#13;
&#13;
&#13;

现在代码的功能正如您所期望的那样saySomethingElse已在最后正确终止。

这是因为,在JavaScript中,您应该在每个语句的末尾使用分号。匿名函数定义是语句,就像任何其他变量定义一样。