javascript 有没有办法检查是否强制执行严格模式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10480108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:01:29  来源:igfitidea点击:

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

javascriptecmascript-5ecma262strict-mode

提问by Deepak Patil

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

无论如何要检查是否强制执行严格模式“使用严格”,并且我们希望为严格模式执行不同的代码,为非严格模式执行其他代码。寻找类似的功能isStrictMode();//boolean

回答by ThiefMaster

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

this在全局上下文中调用的函数内部不会指向全局对象这一事实可用于检测严格模式:

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

回答by Thalaivar

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

看起来你已经得到了答案。但是我已经写了一些代码。所以在这里

回答by noseratio

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 evaldoesn't introduce a new variable into the outer context.

它利用了严格模式下eval不会将新变量引入外部上下文的事实。

回答by Mehdi Golchin

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

this是的'undefined',当您处于严格模式时,它在全局方法中。

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

回答by Mehdi Golchin

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

更优雅的方式:如果“this”是对象,则将其转换为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 )
}

回答by Yaron U.

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

另一种解决方案可以利用在严格模式下声明的变量eval不会暴露在外部作用域中的事实

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