3

I was staring at the angular source code (as I do from time to time) and I was surprised to see the following check:

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)
}

It's part of angular.bind implementation. The full snippet can be found here.

This is the implementation for isFunction (in case you were wondering):

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

Now, let me add this, just in case:

I know what instanceof operator does. It checks to see if a function's prototype (in this case RegExp.prototype) can be found on the prototype chain starting from a particular object.

Now, my question is:

Can you give me an example of a scenario where the above code will follow the else clause? I'm interested in the second part of the expression, I know you can make that condition fail by not providing a function.

That comment warns me about a weird behaviour in IE, but I cannot reproduce it.

  • I have a vague memory that (perhaps only in IE) a RegExp instance is callable as a function. I can't find anything about that with a few googles however. – Pointy Sep 08 '15 at 14:32

2 Answers2

1

In IE7:

typeof window.item // => 'string'

However (in IE7):

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

In IE9:

typeof window.item // => 'function'

In IE11:

typeof window.item // => 'string'
sdgluck
  • 24,894
  • 8
  • 75
  • 90
Petr Averyanov
  • 9,327
  • 3
  • 20
  • 38
  • `typeof window.item` yields "function" on IE11 (on my machine, at least). Also none of these evaluates to true when it comes to the expression `fn instanceof RegExp` –  Sep 08 '15 at 17:14
0

In Netscape's original implementation, RegExp objects were actually functions. re(string) and re.exec(string) were supposed to mean the same thing. In the Netscape and Mozilla browsers, it was supported up through Firefox 4 (released on March 22, 2011). However, typeof stopped returning "function" for RegExp objects even earlier.

It's not the first time a legacy of the Dark Ages has been noticed in the code of Angular. Here is another example. Angular 1.0.0 was released on June 13, 2012.

Community
  • 1
  • 1
thorn0
  • 9,362
  • 3
  • 68
  • 96