为什么我必须在自动执行的匿名函数之前加上分号? [英] Why do I have to put a semicolon before a self executing anonymous function?

查看:40
本文介绍了为什么我必须在自动执行的匿名函数之前加上分号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在大多数情况下,Javascript允许我们在语句末尾省略分号.但是,有趣的是,在这种情况下不是这样:

Most of the cases Javascript permits us to omit a semicolon in the end of a statement. However, interestingly, not in this case:

var x = [5, 'asdf']

(function() {
  window.alert("Yay!")
})()

这是行不通的,除非我们在anon函数之前的语句末尾添加一个分号:

This won't work, unless we put one semicolon in the end of the statement preceding the anon function:

var x = [5, 'asdf'];

(function() {
  window.alert("Yay!")
})()

现在它可以正常工作了.

Now it works perfectly.

在语句末尾有什么晦涩的规则来管理隐含的分号,规定在这种情况下不隐含一个分号?

What obscure rule governing implied semicolons in the ends of statements prescribes that in this case this one semicolon is not implied?

推荐答案

未捕获的TypeError:[5,\"asdf \"]不是函数

Uncaught TypeError: [5,\"asdf\"] is not a function

根据该错误,它认为您的 [5,'asdf'] 是一个函数名,并且您尝试通过参数执行它.如果我们将它们合并成一行,您会看到它类似于将参数传递为函数的函数调用

According to the error it considers that your [5, 'asdf'] is an function name, and you tries to execute it passing the parameters. If we join them in one line, you can see that it is similar to the function call with passed parameter as function

[5, 'asdf'](function() { window.alert("Yay!") })

因此,用分号对编译器说该语句结束,而下一行是另一条语句,即

So putting semicolon says to the compiler that the statement ends, and the next line is another statement which is IIFE.

这篇关于为什么我必须在自动执行的匿名函数之前加上分号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆