【问题标题】:fn instanceof RegExpfn instanceof RegExp
【发布时间】:2015-09-08 14:29:25
【问题描述】:

我盯着 angular 源代码(我不时这样做),我惊讶地看到以下检查:

if (isFunction(fn) && !(fn instanceof RegExp)) {

} else {
  // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
}

它是angular.bind 实现的一部分。完整的 sn-p 可以在here找到。

这是isFunction 的实现(如果您想知道的话):

function isFunction(value) {return typeof value === 'function';}

现在,让我补充一下,以防万一:

我知道instanceof 运算符的作用。它检查是否可以在从特定对象开始的原型链上找到函数的原型(在本例中为 RegExp.prototype)。

现在,我的问题是:

你能给我一个例子,上面的代码将遵循 else 子句吗?我对表达式的第二部分感兴趣,我知道您可以通过不提供函数来使该条​​件失败。

该评论警告我 IE 中的一个奇怪行为,但我无法重现它。

【问题讨论】:

  • 我有一个模糊的记忆(可能仅在 IE 中)RegExp 实例可以作为函数调用。但是,我用一些谷歌搜索找不到任何相关信息。

标签: javascript angularjs


【解决方案1】:

在 IE7 中:

typeof window.item // => 'string'

但是(在 IE7 中):

window.item(0) // => [object] { onbeforeunload: null, ...}

在 IE9 中:

typeof window.item // => 'function'

在 IE11 中:

typeof window.item // => 'string'

【讨论】:

  • typeof window.item 在 IE11 上产生“功能”(至少在我的机器上)。当涉及到表达式 fn instanceof RegExp 时,这些都不会计算为 true
【解决方案2】:

在 Netscape 的原始实现中,RegExp 对象实际上是函数。 re(string)re.exec(string) 应该是同一个意思。在 Netscape 和 Mozilla 浏览器中,它通过 Firefox 4(2011 年 3 月 22 日发布)得到支持。但是,typeof 更早地停止为 RegExp 对象返回 "function"

这不是第一次在 Angular 的代码中注意到黑暗时代的遗产。这里是another example。 Angular 1.0.0 于 2012 年 6 月 13 日发布。

【讨论】:

    猜你喜欢
    • 2014-07-29
    • 2017-08-04
    • 1970-01-01
    • 2018-05-09
    • 2015-02-22
    • 2010-09-23
    • 1970-01-01
    • 2021-03-03
    • 2018-11-10
    相关资源
    最近更新 更多