Search

1/13/2009

perfection kills » Blog Archive » `instanceof` considered harmful (or how to write a robust `isArray`)

perfection kills » Blog Archive » `instanceof` considered harmful (or how to write a robust `isArray`)


function isArray(o) {
return Object.prototype.toString.call(o) === '[object Array]';
}

instanceof considered harmful (or how to write a robust isArray
JavaScript’s instanceof operator breaks when dealing with objects that may have been created in a different document or frame, since constructors are unique to each frame. Instead, you can check for arrays using the default Object.toString method which the JS spec guarantees will return [object Array].

myArray instanceof Array fails after passing to a different page - comp.lang.javascript | Google 網上論壇
When you say 'Array', you are talking about 'window.Array'. 'window' is the
browser's context object, and you get one per page (or frame). All of the arrays
created within a context will have their constructor property set to
'window.Array'.

An array created in a different context has a different window.Array, so your
test
myArray instanceof Array
fails.

/trunk/jquery/src/core.js - jQuery - Development

isFunction: function( obj ) {
return toString.call(obj) === "[object Function]";
},

isArray: function( obj ) {
return toString.call(obj) === "[object Array]";
},

沒有留言: