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)
Tha*_*var 24
function isStrictMode() {
try{var o={p:1,p:2};}catch(E){return true;}
return false;
}
Run Code Online (Sandbox Code Playgroud)
看起来你已经得到了答案.但我已经写了一些代码.所以在这里
nos*_*tio 24
我更喜欢不使用异常并在任何环境中工作的东西,而不仅仅是全局的:
var mode = (eval("var __temp = null"), (typeof __temp === "undefined")) ?
"strict":
"non-strict";
Run Code Online (Sandbox Code Playgroud)
它使用严格模式eval不会在外部上下文中引入新变量的事实.
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)
| 归档时间: |
|
| 查看次数: |
12650 次 |
| 最近记录: |