JavaScript:严格模式和匿名功能

前端之家收集整理的这篇文章主要介绍了JavaScript:严格模式和匿名功能前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
几乎所有的JS文件都被包装在匿名函数中.如果我包含“use strict”;在匿名功能之外,严格模式是否仍然适用于匿名功能

例如,在下面的脚本中,严格模式应用于匿名函数的内部主体:

"use strict";

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

解决方法

根据 John Resig’s article,如果您打开文件顶部的严格模式,它将适用于整个文件/脚本.那么是的,这意味着它将适用于匿名函数.

您还可以在函数添加它,在这种情况下,它仅适用于该特定函数.

编辑添加:这里是the full specification.一个相关段落:

10.1.1 Strict Mode Code

An ECMAScript Program syntactic unit may be processed using either unrestricted or strict mode Syntax and semantics. 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. 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).
  • 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.
  • Function code that is part of a FunctionDeclaration,FunctionExpression,or accessor PropertyAssignment is strict function code if its FunctionDeclaration,or PropertyAssignment is contained in strict mode code or if the function code begins with a Directive Prologue that contains a Use Strict Directive.
  • 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.

猜你在找的JavaScript相关文章