Is there any way to check if strict mode is enforced?

≯℡__Kan透↙ 提交于 2019-11-28 16:16:41

问题


Is there anyway to check if strict mode 'use strict' is enforced , and we want to execute different code for strict mode and other code for non-strict mode. Looking for function like isStrictMode();//boolean


回答1:


The fact that this inside a function called in the global context will not point to 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



回答2:


I prefer something that doesn't use exceptions and works in any context, not only global one:

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

It uses the fact the in strict mode eval doesn't introduce a new variable into the outer context.




回答3:


function isStrictMode() {
    try{var o={p:1,p:2};}catch(E){return true;}
    return false;
}

Looks like you already got an answer. But I already wrote some code. So here




回答4:


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

function isStrictMode() {
    return (typeof this == 'undefined');
}



回答5:


More elegant way: if "this" is 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 )
}



回答6:


Another solution can take advantage of the fact that in strict mode, variables declared in eval are not exposed on the outer scope

function isStrict() {
    var x=true;
    eval("var x=false");
    return x;
}


来源:https://stackoverflow.com/questions/10480108/is-there-any-way-to-check-if-strict-mode-is-enforced

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!