【问题标题】:`use strict` is not working when we use template literals当我们使用模板文字时,`use strict` 不起作用
【发布时间】:2021-05-16 10:31:25
【问题描述】:

如果我用反引号/模板文字将 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 string 只是不适用于模板文字
  • 我更喜欢模板文字,所以尝试过,它是否会在这个特殊的字符串上工作......
  • 当它只是一个简单的字符串时,为什么要使用模板文字? “要为整个脚本调用严格模式,请将确切的语句 "use strict";(或 'use strict';)放在任何其他语句之前。” Source
  • 存在模板文字并不意味着您需要用一个替换每个字符串文字......
  • 您希望`use ${something}`; 为变量something 工作吗?

标签: javascript template-literals use-strict


【解决方案1】:

这是因为 Use Strict Directive 在规范中明确定义为完全由 StringLiteral 产生式组成的 ExpressionStatement,并限制了确切的代码点序列是"use strict"'use strict'

来自ECMAScript 2020 Language Specification

14.1.1 Directive Prologues and the Use Strict Directive

Directive PrologueExpressionStatements 的最长序列,作为初始 StatementListItems@ FunctionBodyScriptBodyModuleBody 的 987654329@s 以及每个 序列中的ExpressionStatement 完全由一个StringLiteral 标记和一个分号组成。分号可以显式出现,也可以通过自动分号插入来插入。 Directive Prologue 可能是一个空序列。

Use Strict DirectiveDirective Prologue 中的 ExpressionStatement,其 StringLiteral 是代码点序列"use strict"'use strict'Use Strict Directive 不能包含 EscapeSequenceLineContinuation

Directive Prologue 可能包含多个Use Strict Directive。但是,如果发生这种情况,实现可能会发出警告。

强调

另一方面,TemplateLiteralStringLiteral 完全不同,因此不能成为有效指令。

【讨论】:

    【解决方案2】:

    就是这样设计的。

    来自ES6 specification

    14.1.1 指令序言和 Use Strict 指令

    指令序言是 ExpressionStatement 产生式的最长序列,作为 FunctionBody 的初始 StatementListItemModuleItem 产生式出现em>、ScriptBodyModuleBody,其中序列中的每个 ExpressionStatement 完全由一个 StringLiteral 标记组成后跟一个分号。分号可以显式出现,也可以由automatic semicolon insertion 插入。指令序言可能是一个空序列。

    Use Strict 指令是指令序言中的一个ExpressionStatement,其StringLiteral 是精确的代码单元序列"use strict"'use strict'。 strong> Use Strict 指令不能包含 EscapeSequenceLineContinuation

    指令序言可能包含多个使用严格指令。但是,如果发生这种情况,实现可能会发出警告。

    强调我的。

    它明确指出,要使 Use Strict 指令起作用,它必须用单引号或双引号编写,但出于此目的根本不允许使用模板文字。

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 2016-08-20
      • 1970-01-01
      • 1970-01-01
      • 2011-07-10
      • 1970-01-01
      • 2015-10-19
      • 1970-01-01
      相关资源
      最近更新 更多