【问题标题】:Is it possible to tell whether a function is in strict mode or not?是否可以判断一个函数是否处于严格模式?
【发布时间】:2012-07-17 22:03:19
【问题描述】:

我的问题可能听起来很奇怪,但是有没有办法通过从另一个函数调用来了解一个函数是否处于严格模式?

function a(){
    "use strict";
    // Body
}

function b(){
// Body
}

function isStrict(fn){

    fn.call();
}

isStrict(a); // true
isStrict(b); // false

【问题讨论】:

  • 我知道这不是我的问题,但我真的不明白在编译时知道它有什么用,除非你在函数中操作回调。在这种情况下,而不是你的回调,传递一个测试回调,它会在严格模式的情况下崩溃,这样你就可以在顶部捕获错误,然后假设严格或不严格。

标签: javascript


【解决方案1】:

当一个函数受到严格模式的影响时,"use strict"; 被添加到前面。所以,下面的检查就可以了:

function isStrict(fn) {
    return typeof fn == 'function' &&
        /^function[^(]*\([^)]*\)\s*\{\s*(["'])use strict\1/.test(fn.toString())
        || (function(){ return this === undefined;})();
}

我使用 RegExp 在函数主体的开头查找 "use strict" 模式。

要检测全局严格模式(这也会影响功能),我会test one of the features 来查看严格模式是否处于活动状态。

【讨论】:

  • 这并不是普遍适用的,比如在严格模式模块模式中定义的闭包。
  • @Bergi 感谢您提供额外信息。 (function() { 'use strict'; return function(){};})().toString() 在 Firefox 中提供 function (){\n"use strict";\n},在 Chrome 中提供 function (){},因此它适用于某些浏览器。
  • 哦,有趣,我不知道 FF 是这样做的
【解决方案2】:

您可以为每个严格的函数添加一个isStrict 属性。

function a() {
    "use strict";
}
a.isStrict = true;

// ...
if ( a.isStrict ) { }

【讨论】:

  • 我想我找到了更好的方法。使用this。
  • 什么意思?如果我将this.isStrict = true 放在函数中,则需要调用该函数来设置 isStrict 属性。
  • 我同意 Esailija 的回答。您不必调用该函数,因为这可能会导致不必要的副作用。
  • 谢谢。解析似乎是解决方案。
猜你喜欢
  • 2010-10-13
  • 2011-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-28
相关资源
最近更新 更多