简体   繁体   English

JavaScript:严格模式和匿名函数

[英]JavaScript: Strict mode and anonymous functions

Nearly all my JS files are wrapped in anonymous functions. 我几乎所有的JS文件都包装在匿名函数中。 If I include "use strict"; 如果我包括"use strict"; outside the anonymous function, is strict mode still applied to the anonymous function? 在匿名函数之外,严格模式是否仍适用于匿名函数?

For example, is strict mode applied to the inner body of the anonymous function in the script below: 例如,以下脚本中是否将严格模式应用于匿名函数的内部:

"use strict";

(function() {
    // Is this code running under strict mode?
})(); 

According to John Resig's article , if you turn on strict mode at the top of the file, it applies to the entire file/script. 根据John Resig的文章 ,如果打开文件顶部的严格模式,则该模式将应用于整个文件/脚本。 So yes, that implies that it would apply within the anonymous function. 是的,这意味着它将在匿名函数中应用。

You can also add it within a function, in which case it only applies to that specific function. 您也可以将其添加到函数中,在这种情况下,它仅适用于该特定函数。

Edited to add: here's the full specification . 编辑添加:这是完整的规范 One relevant paragraph: 一个相关的段落:

10.1.1 Strict Mode Code 10.1.1严格模式代码

An ECMAScript Program syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. 可以使用非限制或严格模式的语法和语义来处理ECMAScript程序语法单元。 When processed using strict mode the three types of ECMAScript code are referred to as strict global code, strict eval code, and strict function code. 使用严格模式处理时,三种ECMAScript代码称为严格全局代码,严格评估代码和严格功能代码。 Code is interpreted as strict mode code in the following situations: 在以下情况下,代码被解释为严格模式代码:

  • Global code is strict global code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1). 如果全局代码以包含使用严格指令的指令序言开头(请参阅14.1),则它是严格的全局代码。
  • Eval code is strict eval code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct call (see 15.1.2.1.1) to the eval function that is contained in strict mode code. 如果Eval代码以包含使用严格指令的指令序言开头,或者如果eval的调用是对严格模式代码中包含的eval函数的直接调用(请参见15.1.2.1.1),则Eval代码是严格的Eval代码。
  • Function code that is part of a FunctionDeclaration, FunctionExpression, or accessor PropertyAssignment is strict function code if its FunctionDeclaration, FunctionExpression, or PropertyAssignment is contained in strict mode code or if the function code begins with a Directive Prologue that contains a Use Strict Directive. 如果FunctionDeclaration,FunctionExpression或访问器PropertyAssignment的一部分的功能代码包含在严格模式代码中,或者如果该功能代码以包含使用严格指令的指令序言开头,则该功能代码为严格功能代码。
  • Function code that is supplied as the last argument to the built-in Function constructor is strict function code if the last argument is a String that when processed as a FunctionBody begins with a Directive Prologue that contains a Use Strict Directive. 作为最后一个参数提供给内置Function构造函数的函数代码是严格的函数代码,前提是最后一个参数是一个字符串,当作为FunctionBody处理时,该字符串以包含使用严格指令的指令序言开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM