缺少分号会意外破坏脚本
注意:最初,我认为该问题是由更复杂的原因引起的;我现在看到(并编辑了标题和示例代码)唯一的区别是分号的存在或不存在。这可能会让这个问题变得理所当然地回答,但我仍然惊讶地发现在这种情况下尾随分号很重要,而不是其他...
为什么这有效:
<script type="text/javascript">
this.someFunc = function () {};
(function () {
console.log("self-invoking function called.")
})();
</script>
但这不起作用:
<script type="text/javascript">
this.someFunc = function () {}
(function () {
console.log("self-invoking function called.")
})();
</script>
然而,这确实有效:
<script type="text/javascript">
this.someFunc = function () {}
var someVar = "value";
console.log("someVar is:"+someVar);
</script>
后者将自调用函数解释为未定义
,因此无法评估/执行它。在 OSX 上的 Chrome 13、Firefox 6 和 Safari 5 上进行了测试。
NOTE: originally, I thought the issue was caused by something more complex; I see now (and edited the title and sample code) that the only difference is the presence or absence of a semicolon. That may make this a no-brainer to answer, but I was still surprised to see a trailing semicolon matters in this case and not others...
Why does this work:
<script type="text/javascript">
this.someFunc = function () {};
(function () {
console.log("self-invoking function called.")
})();
</script>
but this does not:
<script type="text/javascript">
this.someFunc = function () {}
(function () {
console.log("self-invoking function called.")
})();
</script>
and yet, this does:
<script type="text/javascript">
this.someFunc = function () {}
var someVar = "value";
console.log("someVar is:"+someVar);
</script>
The latter interprets the self-invoking function as undefined
, and therefore cannot evaluate/execute it. Tested on Chrome 13, Firefox 6, and Safari 5 on OSX.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信第二个片段实际上是在执行空函数声明。如果将示例更改为:
然后运行 (FF6),您将看到它记录:
function()
。它传入第二个匿名函数作为第一个匿名函数的参数。如果您重新排列,这会更有意义:I believe the second snippet is actually executing the empty function declaration. If you change your example to this:
and then run (FF6), you will see that it logs:
function()
. It's passing in the second anonymous function as an argument for the first. This makes more sense if you rearrange:只需查看问题右侧的第一个相关主题: 为什么我应该在 javascript 中的每个函数后面使用分号?
接受的答案很好地解释了这种行为。
Just looking at the first Related topic on the right of your question: Why should I use a semicolon after every function in javascript?
The accepted answer is a great explanation of this behavior.