Reputation: 777
When I attempt to run
function isRegExp(value) {
return toString.call(value) === '[object RegExp]';
}
in IE <= 11 (tried on 11 and 9), I get a TypeError: Invalid calling object
. This code works in newer versions as well as other browsers.
Firstly, I am confused. This function is identical to the AngularJS function, and Angular claims to support IE 9+. How is it that the same line of code, when I use it, causes an error (and thus causes my calling function to break), when I assume they have tested it already?
Secondly, I am curious about what exactly could be causing the issue. This value can be anything in Javascript, and it only seems to be breaking with some of the things I send it (it doesn't seem to break when just given a simple array, but seems to struggle with arrays of objects of arrays of objects...ect.)
Upvotes: 2
Views: 2377
Reputation: 13071
If you want to do the exact same thing that Angular is doing you should be doing it like this:
function isRegExp(value) {
return Object.prototype.toString.call(value) === '[object RegExp]';
}
Notice this section of code that defines the shortcut toString
.
Example:
var toString = Object.prototype.toString;
function isRegExp(value) {
return toString.call(value) === '[object RegExp]';
}
snippet.log(isRegExp(/foo/)); // true
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
The reason for doing this toString
thing rather than instanceof
or similar is that the behavior of Object.prototype.toString
is very well-defined in the spec, and this technique works even when the RegExp
object you're testing came from another window, whereas using instanceof
doesn't work in that case. Here's an example showing that: http://jsbin.com/sehivi
Upvotes: 7