Where is the documentation for the built-in JavaScript function toString?
I was looking through the jQuery code and found that isArray is implemented using the built-in function toString. I cannot find the documentation for this function on MDC. D开发者_JAVA技巧oes the doc exist? What does this function do?
isArray: function( obj ) {
return toString.call(obj) === "[object Array]";
},
I was looking through the jQuery code and found that isArray is implemented using the built-in function toString
It's not a builtin. See line 68:
toString = Object.prototype.toString,
jQuery is taking a copy of the toString
method on Object
under its own variable named toString
. The Object#toString
method is documented at MDC here (and by ECMAScript itself). jQuery then calls the variable copy of the method using call
and passing in the object as this
. This roundabout calling method is so that you can't make an object that overrides toString()
and might return the string '[object Array]'
.
(In particular, the string '[object Array]'
itself would have [object Array]
as its toString()
value, and so would erroneously be detected as an Array, if the obj.toString()
were called directly. Calling Object
's base implementation of toString()
avoids this.)
Testing the toString()
representation is ugly as hell (and still not quite 100% in the case of host objects), but the more straightforward obj instanceof Array
doesn't work for cross-window-scripting, since Array
is a different constructor in each window/frame.
ECMAScript Fifth Edition adds the function Array.isArray(obj)
to avoid this unpleasantness. Browser support is currently poor, however.
精彩评论