javascript - (function eval () {}) 如果函数体处于严格模式会抛出语法错误?

标签 javascript theory

为什么这段代码会抛出错误?

// global non-strict code
(function eval () { 'use strict'; });

现场演示: http://jsfiddle.net/SE3eX/1/

所以,我们这里有一个命名函数表达式。我想明确指出这个函数表达式出现在非严格代码中。如您所见,它的函数体是严格的代码。

严格模式规则在这里:http://ecma-international.org/ecma-262/5.1/#sec-C

相关项目符号是这个(它是列表中的最后一个):

It is a SyntaxError to use within strict mode code the identifiers eval or arguments as the Identifier of a FunctionDeclaration or FunctionExpression or as a formal parameter name (13.1). Attempting to dynamically define such a strict mode function using the Function constructor (15.3.2) will throw a SyntaxError exception.

请注意此规则如何仅在函数声明/表达式本身出现在严格代码中时适用,而在我上面的示例中

但是还是报错?为什么?

最佳答案

§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:

  1. 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:

  1. 它是从 use strict 上下文中调用的。
  2. 它的函数体以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

关于javascript - (function eval () {}) 如果函数体处于严格模式会抛出语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12569195/

相关文章:

javascript - 引用错误 : Can't find variable: jQuery with Poltergeist/Capybara

javascript - 无法读取 null 的属性 'insertBefore' - handsontable.full.js :3714

oop - 耦合性和内聚性

javascript - 无法向 JavaScript 数组中的对象添加新属性

javascript - 在谷歌地图上禁用巴士站

python - 返回值比设置全局变量有什么优势吗?

algorithm - 今天我的算法测验中的图论问题,我想帮助理解

algorithm - 证明决策概率在 NP 中

java - 使用 diffie-hellman 共享 key 继续加密

javascript - 如何使 SJCL 和 Python hashlib 生成相同的 pdkdf2 输出