【问题标题】:Is there any way to check if strict mode is enforced?有什么方法可以检查是否强制执行严格模式?
【发布时间】:2012-05-07 10:00:03
【问题描述】:

是否有办法检查严格模式“使用严格”是否被强制执行,我们想为严格模式执行不同的代码,为非严格模式执行其他代码。 寻找像isStrictMode();//boolean这样的函数

【问题讨论】:

    标签: javascript ecmascript-5 ecma262 strict-mode


    【解决方案1】:

    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是否存在。
    【解决方案2】:

    我更喜欢不使用异常并且可以在任何上下文中工作的东西,而不仅仅是全局:

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

    它使用严格模式eval 不会将新变量引入外部上下文这一事实。

    【讨论】:

    • 只是出于好奇,既然 ES6 来了,这在 2015 年有多防弹?
    • 我验证它在最新的 chrome 和 nodejs 上的 ES6 中工作。
    • 不错!在带有/不带有 --use_strict 标志的 NodeJS 10 REPL 中工作。
    【解决方案3】:
    function isStrictMode() {
        try{var o={p:1,p:2};}catch(E){return true;}
        return false;
    }
    

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

    【讨论】:

    • 这比 Mehdi 的回答要好,因为它可以在任何地方工作,而不仅仅是在全球范围内。上升。 :)
    • 这会导致语法错误,发生在代码运行之前,所以无法捕获...
    • 这在 ES6 中也不起作用,因为删除了检查以允许计算属性名称。
    • 为什么要在严格模式下抛出错误?
    • @skerit 你能详细说明你的语法错误吗?我没有得到。
    【解决方案4】:

    是的,当您处于严格模式时,this 是全局方法中的 'undefined'

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

    【讨论】:

      【解决方案5】:

      警告+通用解决方案

      这里的许多答案都声明了一个检查严格模式的函数,但是这样的函数不会告诉你它被调用的范围,只会告诉你它被声明的范围!

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

      与跨脚本标签调用相同。

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

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

      与最受欢迎的答案不同,Yaron 的这项检查不仅适用于全球范围。

      【讨论】:

        【解决方案6】:

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

        【讨论】:

          【解决方案7】:

          另一个解决方案可以利用这样一个事实,即在严格模式下,eval 中声明的变量不会暴露在外部作用域中

          function isStrict() {
              var x=true;
              eval("var x=false");
              return x;
          }
          

          【讨论】:

            猜你喜欢
            • 2018-07-18
            • 1970-01-01
            • 2018-02-15
            • 2014-05-26
            • 1970-01-01
            • 1970-01-01
            • 2021-10-30
            • 1970-01-01
            • 2011-01-17
            相关资源
            最近更新 更多