What is Prologue Directives?

2019-04-29 12:16发布

I stumbled upon something people choose to call Prologue Directives. More commonly known with the "use strict"; string literal in JavaScript. Which i already know all about. But the common denominator Prologue Directive. What it is? There's very little documentation available on this subject. Best one is the question i linked.

ECMAScript multiple Prologue Directives

My questions are generic:

What are they?

What can they be used for?

Who uses them and why?

Can i make them?

Should i?

1条回答
Bombasti
2楼-- · 2019-04-29 12:50

No need for documentation. Just look in 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.

In other words, Directive Prologue is the longest sequence of string literal + semicolon at the exact start of function or program (top-level code):

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

or:

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

or:

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

Notice that as soon as the string literal is not the first statement, it's no longer a Directive Prologue:

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

or:

(function() {
  1 + "use magic"; // <-- NOT a Directive Prologue
})();
查看更多
登录 后发表回答