当我们使用模板文字时,`use strict` 不起作用

`use strict` is not working when we use template literals

如果我用 backticks/template 文字将 use strict 括起来,'use strict' 将无法正常工作。你能分享一下背后的原因吗?是否有任何类似的异常语句,其中模板文字不会按预期工作?

`use strict`;
x = 3.14;  // Ideally it should  cause an error (as x is not defined).
alert(x);

`use strict`; // if we enclose in single quotes or double quotes
x = 3.14;    // Ideally it should  cause an error (as x is not defined).
alert(x);

那是因为 Use Strict Directive is explicitly defined in the specification as an ExpressionStatement consisting entirely of a StringLiteral 的产生,并将确切的代码点序列限制为 "use strict"'use strict'

来自ECMAScript 2020 Language Specification:

14.1.1 Directive Prologues and the Use Strict Directive

A Directive Prologue is the longest sequence of ExpressionStatements occurring as the initial StatementListItems or ModuleItems of a FunctionBody, a ScriptBody, or a ModuleBody and where each ExpressionStatement in the sequence consists entirely of a StringLiteral token followed by 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 of the exact code point 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.

已强调

另一方面,TemplateLiteral is an entirely different production than a StringLiteral,因此不是有效指令。

就是这么设计的

来自ES6 specification

14.1.1 Directive Prologues and the Use Strict Directive

A Directive Prologue is the longest sequence of ExpressionStatement productions occurring as the initial StatementListItem or ModuleItem productions of a FunctionBody, a ScriptBody, or a ModuleBody and where each ExpressionStatement in the sequence consists entirely of a StringLiteral token followed by 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 code unit 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.

强调我的。

它清楚地指出,为了使 Use Strict 指令起作用,它必须用单引号或双引号引起来,但模板文字根本不允许用于此目的。