最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript: Strict mode and anonymous functions - Stack Overflow

programmeradmin3浏览0评论

Nearly all my JS files are wrapped in anonymous functions. If I include "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?
})(); 

Nearly all my JS files are wrapped in anonymous functions. If I include "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?
})(); 
Share Improve this question asked May 16, 2011 at 17:17 FoobarisMaximusFoobarisMaximus 1,1293 gold badges13 silver badges18 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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

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, 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.
  • 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.
发布评论

评论列表(0)

  1. 暂无评论