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

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

本文关键字:模式 强制执行 是否 检查 有没有      更新时间:2023-09-26

有没有办法检查是否强制执行严格模式"使用严格",并且我们想为严格模式执行不同的代码,为非严格模式执行其他代码。查找类似isStrictMode();//boolean<</p>

div class="answers"的函数> 在

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

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

演示:

> echo '"use strict"; var isStrict = (function() { return !this; })(); console.log(isStrict);' | node
true
> echo 'var isStrict = (function() { return !this; })(); console.log(isStrict);' | node
false

我更喜欢不使用异常并且适用于任何上下文的东西,而不仅仅是全局上下文:

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

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

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

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

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

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

警告 + 通用解决方案

这里的许多答案都声明了一个函数来检查严格模式,但这样的函数不会告诉你它被调用的范围,只会告诉你声明它的范围!

function isStrict() { return !this; };
function test(){
  'use strict';
  console.log(isStrict()); // false
}

与跨脚本标记调用相同。

因此,每当您需要检查严格模式时,都需要在该范围内编写整个检查:

var isStrict = true;
eval("var isStrict = false");

与最受好评的答案不同,Yaron的这张支票不仅适用于全球范围。

更优雅的方式:如果"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 )
}

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

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