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

Dee*_*til 68 javascript ecma262 ecmascript-5 strict-mode

无论如何都要检查是否强制执行严格模式'use strict',并且我们想要为严格模式执行不同的代码,而为非严格模式执行其他代码.寻找像这样的功能isStrictMode();//boolean

Thi*_*ter 89

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

var isStrict = (function() { return !this; })();
Run Code Online (Sandbox Code Playgroud)

演示:

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

  • 为了澄清起见,return 语句等同于 `return this === undefined`,它不是将它与全局对象进行比较,它只是检查 `this` 是否存在。 (3认同)

Tha*_*var 24

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

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

  • 这导致语法错误,这在代码运行之前发生,因此无法捕获... (7认同)
  • 这在ES6中不起作用,因为删除了检查以允许计算属性名称. (5认同)

nos*_*tio 24

我更喜欢不使用异常并在任何环境中工作的东西,而不仅仅是全局的:

var mode = (eval("var __temp = null"), (typeof __temp === "undefined")) ? 
    "strict": 
    "non-strict";
Run Code Online (Sandbox Code Playgroud)

它使用严格模式eval不会在外部上下文中引入新变量的事实.

  • 我验证它在最新的chrome和nodejs上的ES6中有效. (3认同)
  • 好的!在带有/不带有“--use_strict”标志的 NodeJS 10 REPL 中工作。 (2认同)

pot*_*ato 11

警告+通用解决方案

这里的许多答案都声明了一个函数来检查严格模式,但是这样的函数不会告诉您有关它调用的范围的任何信息,只会告诉您声明它的范围!

function isStrict() { return !this; };

function test(){
  'use strict';
  console.log(isStrict()); // false
}
Run Code Online (Sandbox Code Playgroud)

与跨脚本标签调用相同。

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

var isStrict = true;
eval("var isStrict = false");
Run Code Online (Sandbox Code Playgroud)

与最受支持的答案不同,Yaron 的这项检查不仅在全球范围内有效。


Meh*_*hin 10

是的,this'undefined'一个全球性的方法中,当你在严格模式.

function isStrictMode() {
    return (typeof this == 'undefined');
}
Run Code Online (Sandbox Code Playgroud)


小智 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 )
}
Run Code Online (Sandbox Code Playgroud)