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. Does the doc exist? What does this function do?
isArray: function( obj ) {
return toString.call(obj) === "[object Array]";
},
It’s not a builtin. See line 68:
jQuery is taking a copy of the
toStringmethod onObjectunder its own variable namedtoString. TheObject#toStringmethod is documented at MDC here (and by ECMAScript itself). jQuery then calls the variable copy of the method usingcalland passing in the object asthis. This roundabout calling method is so that you can’t make an object that overridestoString()and might return the string'[object Array]'.(In particular, the string
'[object Array]'itself would have[object Array]as itstoString()value, and so would erroneously be detected as an Array, if theobj.toString()were called directly. CallingObject‘s base implementation oftoString()avoids this.)Testing the
toString()representation is ugly as hell (and still not quite 100% in the case of host objects), but the more straightforwardobj instanceof Arraydoesn’t work for cross-window-scripting, sinceArrayis 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.