注释可以出现在 `use strict;` 之前吗?

Can comments come before `use strict;`?

我在互联网上看到一些地方被动地声明 'use strict;' 必须出现在您希望行为指令针对的功能范围的 first 行申请。

不过,根据我的经验,前面有没有评论也没关系。

/* some comment */
'use strict';

将注释放在指令之前是否存在功能性缺陷,还是纯粹是风格问题?这是在 ECMAScript 规范中的任何地方定义的吗?

我要求的不仅是 V8 (node.js) 环境,还有浏览器。

是的,您可以在 "use strict"; 之前添加评论——它必须出现在任何 声明 之前。

请参阅 MDN

中的示例
// Whole-script strict mode syntax
"use strict";
var v = "Hi!  I'm a strict mode script!";

是的。注释可以放在 "use strict" 声明之前。 JavaScript 引擎只是跳过注释,因此就所有意图和目的而言,"use strict" 语句位于功能范围的顶部。

According to MDNuse strict; 必须是脚本或函数中的第一个 语句 。评论不是陈述。

根据 ECMAScript 262 第 5 版标准部分 14.1:

. . . the initial SourceElement productions of a Program or FunctionBody and where each ExpressionStatement in the sequence consists entirely of a StringLiteral token followed a semicolon

强调我的

和 ECMAScript 262 第 6 版标准部分 14.1.1:

A Directive Prologue is . . . the initial StatementListItem or ModuleItem productions of a FunctionBody, a ScriptBody, or a ModuleBody.

强调我的


也许更简单地说,ECMAScript 第 6 版的 7.4 of the ECMAScript 5th ed. standard (section 11.4 部分。标准)状态:

Comments behave like white space and are discarded

由于注释不是语句并且最终会被丢弃,因此 use strict; 可以在注释之后出现,因为它是正文中的第一个有效语句。


多年后更新 - 或多或少,更多上下文。

大多数解析器都有一个词法分析步骤和一个解析步骤。第一个是词法分析,将文本源代码分解为更明显的标记(例如 left angle bracketidentifiercommastring literal 等),解析步骤实际上是 对他们做一些事情——在很多情况下(当然在Javascript的情况下),把它变成所谓的Abstract Syntax Tree(或简称AST)。

有两件事造成了这个 "allowed",尤其是根据 this comment - 一个是评论将被丢弃,这通常发生在 lexing 期间,并且 'use strict'; 必须是第一个语句,通常在 parsing.

期间检查

由于词法分析先于解析,因此 'use strict'; 的检查实际上永远不会 看到 评论甚至有可能出现问题。