首页 > 解决方案 > 当我们使用模板文字时,`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);

标签: javascripttemplate-literalsuse-strict

解决方案


它就是这样设计的。

来自ES6 规范

14.1.1 指令序言和使用严格指令

指令序言是最长的ExpressionStatement产生序列,作为FunctionBodyScriptBodyModuleBody的初始StatementListItemModuleItem产生出现,其中序列中的每个ExpressionStatement完全由一个StringLiteral标记和一个分号组成。分号可以显式出现,也可以通过自动分号插入来插入。指令序言可能是一个空序列。

Use Strict Directive 是 Directive Prologue 中的ExpressionStatement,其StringLiteral是确切的代码单元序列"use strict"'use strict'. 使用严格指令可能不包含EscapeSequenceLineContinuation

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

强调我的。

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


推荐阅读