为什么在行尾需要分号? [英] Why is a semicolon required at end of line?

查看:136
本文介绍了为什么在行尾需要分号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这样做:

a = []
a.push(['test']);
(function() {alert('poop')})()

但是这个给出错误数字不是函数:

But this gives the error "number is not a function":

a = []
a.push(['test'])
(function() {alert('poop')})()

唯一的区别是第2行末尾的分号。我已经写了很长时间的JavaScript了。我知道自动分号插入,但我无法弄清楚会导致此错误的原因。

The only difference is the semicolon at the end of line 2. I've been writing JavaScript for a long time now. I know about automatic semicolon insertion, but I can't figure out what would be causing this error.

推荐答案

看看这个链式函数调用的例子。

Take a look at this example of chained function calls.

a.push(['test'])(function() {alert('poop')})()

看起来很熟悉?这就是编译器/解释器查看代码的方式。

Look familiar? This is how the compiler/interpreter views your code.

明细

以下是用于描述调用表达式的语法的一部分。

Here is a portion of the grammar used to describe call expressions.


CallExpression : 
	MemberExpression Arguments 
	CallExpression Arguments 
	CallExpression [ Expression ] 
	CallExpression . IdentifierName 

基本上每个组(...)被视为参数到原始的 MemberExpression a.push

Essentially each group (...) is considered as Arguments to the original MemberExpression a.push.

a.push (['test'])                // MemberExpression Arguments 
(function() {alert('poop')})     // Arguments  
()                               // Arguments 

或更正式


CallExpression(
    CallExpression(  
        CallExpression(
            MemberExpression( a.push ),
            Arguments( (['test']) )
        ),
        Arguments( (function() {alert('poop')}) )
    ),
    Arguments( () )
)

这篇关于为什么在行尾需要分号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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