什么是序言指令?

What is Prologue Directives?

我偶然发现了一些人们选择称之为序言指令的东西。更常见的是 "use strict"; JavaScript 中的字符串文字。我已经知道了。但共同点序言指令。这是什么?关于这个主题的文档很少。最好的一个是我链接的问题。

ECMAScript multiple Prologue Directives

我的问题很笼统:

它们是什么?

它们有什么用?

谁在使用它们,为什么?

我可以做吗?

我应该吗?

无需文档。看看 the source.

A Directive Prologue is the longest sequence of ExpressionStatement productions occurring as 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. The semicolon may appear explicitly or may be inserted by automatic semicolon insertion. A Directive Prologue may be an empty sequence.

A Use Strict Directive is an ExpressionStatement in a Directive Prologue whose StringLiteral is either the exact character sequences "use strict" or 'use strict'. A Use Strict Directive may not contain an EscapeSequence or LineContinuation.

A Directive Prologue may contain more than one Use Strict Directive. However, an implementation may issue a warning if this occurs.

换句话说,指令序言是函数或程序(顶级代码)确切开始处的字符串文字+分号的最长序列:

(function(){
  "use strict"; // <-- Directive Prologue
})()

或:

(function() {
  // Directive Prologue start
  "foo bar"
  "baz";
  '123';
  '';
  // Directive Prologue end
})();

或:

'blah'; // <-- Directive Prologue (top-level code)
/* rest of the code here */

请注意,一旦字符串文字不是第一条语句,它就不再是指令序言:

var x;
"use strict"; // <-- NOT a Directive Prologue

或:

(function() {
  1 + "use magic"; // <-- NOT a Directive Prologue
})();