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

96

有没有一种方法可以检查是否强制使用严格模式"use strict",我们想要在严格模式下执行不同的代码,在非严格模式下执行其他代码。

寻找类似isStrictMode(); // 布尔值的函数。


你可以使用 (() => !this)(),例如 (() => !this)() ? "strict" : "sloppy" - Eljay
7个回答

127

在全局上下文中调用的函数内部,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

11
为澄清一下,return 语句等价于 return this === undefined,它并不是将其与全局对象进行比较,而只是检查 this 是否存在。 - aljgom

38

我更喜欢使用不需要异常处理,并且可以在任何上下文中工作的解决方案,而不仅仅是全局性的解决方案:

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

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


只是出于好奇,现在ES6已经到来,这个在2015年有多牢固? - John Weisz
3
我验证过它可以在最新的Chrome和Node.js上运行ES6。 - Michael Matthew Toomim
2
不错!在 NodeJS 10 REPL 中可以使用/不使用 --use_strict 标志。 - igor
不会影响应用程序的性能,尤其是 React 应用。 - ellockie
1
@ellockie 我不会在紧密的渲染循环中这样做,但作为每个模块初始化的一次性操作,我认为没有问题。无论如何,在2023年可能会有更好的方法来实现这一点。 - noseratio

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

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


1
这个比Mehdi的回答更好,因为它可以在任何地方工作,而不仅仅是在全局范围内。点赞 :) - mgol
7
这会导致语法错误,在代码运行之前就发生了,因此无法捕获... - Jelle De Loecker
7
这在 ES6 中也不起作用,因为已经移除了检查,以允许计算属性名。 - billc.cn
1
在严格模式下为什么应该抛出错误? - Buksy
1
@skerit,你能详细说明一下你的语法错误吗?我没有遇到过这种情况。 - Robert Siemer
规范和引擎的行为已经改变。现在旧引擎会抛出异常,但新引擎不会抛出异常。https://dev59.com/sF0a5IYBdhLWcg3wLWGx - shitpoet

16

在严格模式下,当你在全局方法中时,this会被定义为'undefined'

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

11

警告 + 通用解决方案

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

function isStrict() { return !this; };

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

跟跨脚本标签调用一样。

所以每当你需要检查严格模式时,你需要在该范围内编写完整的检查:

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

与最得票的答案不同,Yaron的这个检查不仅适用于全局范围。

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

0
另一种解决方案可以利用严格模式下,eval声明的变量不会暴露在外部作用域的事实。
function isStrict() {
    var x=true;
    eval("var x=false");
    return x;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接