有没有一种方法可以检查是否强制使用严格模式"use strict",我们想要在严格模式下执行不同的代码,在非严格模式下执行其他代码。
寻找类似isStrictMode(); // 布尔值
的函数。
有没有一种方法可以检查是否强制使用严格模式"use strict",我们想要在严格模式下执行不同的代码,在非严格模式下执行其他代码。
寻找类似isStrictMode(); // 布尔值
的函数。
在全局上下文中调用的函数内部,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
return
语句等价于 return this === undefined
,它并不是将其与全局对象进行比较,而只是检查 this
是否存在。 - aljgom我更喜欢使用不需要异常处理,并且可以在任何上下文中工作的解决方案,而不仅仅是全局性的解决方案:
var mode = (eval("var __temp = null"), (typeof __temp === "undefined")) ?
"strict":
"non-strict";
它利用了在严格模式下eval
不会将新变量引入到外部上下文的事实。
--use_strict
标志。 - igorfunction 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");
"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 )
}
function isStrict() {
var x=true;
eval("var x=false");
return x;
}
(() => !this)()
,例如(() => !this)() ? "strict" : "sloppy"
。 - Eljay