【发布时间】:2012-05-07 10:00:03
【问题描述】:
是否有办法检查严格模式“使用严格”是否被强制执行,我们想为严格模式执行不同的代码,为非严格模式执行其他代码。
寻找像isStrictMode();//boolean这样的函数
【问题讨论】:
标签: javascript ecmascript-5 ecma262 strict-mode
是否有办法检查严格模式“使用严格”是否被强制执行,我们想为严格模式执行不同的代码,为非严格模式执行其他代码。
寻找像isStrictMode();//boolean这样的函数
【问题讨论】:
标签: javascript ecmascript-5 ecma262 strict-mode
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 this === undefined,它不是将它与全局对象进行比较,它只是检查this是否存在。
我更喜欢不使用异常并且可以在任何上下文中工作的东西,而不仅仅是全局:
var mode = (eval("var __temp = null"), (typeof __temp === "undefined")) ?
"strict":
"non-strict";
它使用严格模式eval 不会将新变量引入外部上下文这一事实。
【讨论】:
--use_strict 标志的 NodeJS 10 REPL 中工作。
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;
}
【讨论】: