§13.1概括应该是什么的情况下,如你发生:
- It is a SyntaxError if any Identifier value occurs more than once within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression.
- It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs within a - FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression.
- It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the Identifier of a strict mode FunctionDeclaration or FunctionExpression.
重点煤矿。您的严格模式功能的标识符是eval
,因此它是SyntaxError
。游戏结束。
明白为什么上面是一个“严格模式的功能表现,”看语义定义在§13(函数定义):
The production
FunctionExpression : function
Identifieropt(
FormalParameterListopt) {
FunctionBody}
is evaluated as follows:
- Return the result of creating a new Function object as specified in 13.2 with parameters specified by FormalParameterListopt and body specified by FunctionBody. Pass in the LexicalEnvironment of the running execution context as the Scope. Pass in true as the Strict flag if the FunctionExpression is contained in strict code or if its FunctionBody is strict code.
重点煤矿。以上显示了函数表达式(或声明)如何变得严格。它说什么(用简单的英语)是一个FunctionExpression有两种strict
情况:
- 它从
use strict
上下文调用。
- 其功能主体以
use strict
开头。
你的困惑从思想出现,只有函数体是strict
,而事实上,整个函数表达式是strict
。你的逻辑虽然直观,但并不是JS的工作方式。
如果您想知道为什么ECMAscript以这种方式工作,这很简单。假设我们有这样的:
// look ma, I'm not strict
(function eval() {
"use strict";
// evil stuff
eval(); // this is a perfectly legal recursive call, and oh look...
// ... I implicitly redefined eval() in a strict block
// evil stuff
})();
值得庆幸的是,上面的代码将抛出,因为整个函数表达式被标记为strict
。
这里只是完全猜测,但也许它与这样的事实有关:在*表达式*中,具有名称的函数实例化表达式仅在该函数内将该名称绑定*;换句话说,它在内部就好像有一种'var'声明创建一个局部变量的魔术方式,该局部变量是通过引用该函数来初始化的。因此,就好像你试图在本地绑定全局符号“eval”。 – Pointy
@Pointy好提示。我将不得不检查标准以确定在该场景中到底发生了什么...... –
只有函数eval()会得到相同的错误消息(SyntaxError:函数名称不能是eval或严格模式下的参数) {'严格使用'; };' – some