gpt4 book ai didi

javascript - 为什么没有分号的代码在 JavaScript 中仍然可以工作?

转载 作者:行者123 更新时间:2023-12-02 16:20:58 26 4
gpt4 key购买 nike

在 JavaScript 中,如何在没有 ; 的情况下调用函数?

示例

假设 testMethod 已在某处声明...

testMethod();

testMethod() // Without semicolon will still work.

同时调用元素内的方法示例:

<input type="button" onclick="testMethod();" />
<input type="button" onclick="testMethod()" /> // Again no semicolon.

最佳答案

这是一个称为“自动分号插入”(或 ASI)的功能。

来自Dealing with JavaScript's Automatic Semicolon Insertion

So how are these semicolons inserted for you? By following these rules (paraphrased and simplified from ECMA-262 3rd edition, 7.9.1):

  • When, as the program is parsed, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true:
    1. The offending token is separated from the previous token by at least one LineTerminator.
    2. The offending token is }.
  • When the end of the input stream of tokens is encountered and the parser is unable to parse the input token stream as a single complete program, then a semicolon is automatically inserted at the end of the input stream.
  • A token is a restricted token when it is allowed by some production of the grammar, but the production is a restricted production and the token would be the first token for a terminal or nonterminal immediately following the annotation “[no LineTerminator here]” within the production.

If furthermore the restricted token is separated from the previous token by at least one LineTerminator, then a semicolon is automatically inserted before the restricted token.

...

关于javascript - 为什么没有分号的代码在 JavaScript 中仍然可以工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10589135/

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