Is there a way to check if strict mode is set?

In any case, we need to check if the "use strict" mode is applied, and we want to execute different code for the strict mode and a different code for the non-strict mode. Search for functions of type isStrictMode();//boolean

+46
javascript ecma262 ecmascript-5 strictmode
May 7, '12 at 10:00
source share
5 answers

The fact that this inside a function called in a global context will not indicate that the global object can be used to detect strict mode:

 var isStrict = (function() { return !this; })(); 

Demo:

 > echo '"use strict"; var isStrict = (function() { return !this; })(); console.log(isStrict);' | node true > echo 'var isStrict = (function() { return !this; })(); console.log(isStrict);' | node false 
+58
May 7 '12 at 10:08
source share
 function isStrictMode() { try{var o={p:1,p:2};}catch(E){return true;} return false; } 

It looks like you already have an answer. But I already wrote the code. So here

+18
May 7 '12 at 10:36
source share

I prefer that it does not use exceptions and works in any context, and not just global:

 var mode = (eval("var __temp = null"), (typeof __temp === "undefined")) ? "strict": "non-strict"; 

It exploits the fact that in strict mode, eval does not introduce a new variable into the external context.

+15
Sep 20 '13 at 12:26
source share

Yep, this is 'undefined' in the global method when you are in strict mode.

 function isStrictMode() { return (typeof this == 'undefined'); } 
+7
May 7 '12 at 10:07
source share

More elegant way: if "this" is an object, convert it to true

 "use strict" var strict = ( function () { return !!!this } ) () if ( strict ) { console.log ( "strict mode enabled, strict is " + strict ) } else { console.log ( "strict mode not defined, strict is " + strict ) } 
0
Aug 30 '16 at 10:42 on
source share



All Articles