Identifying which objects are which is complicated in JavaScript, and figuring out which objects are arrays has something of a hacky solution. Fortunately, it manages to work in both of the following cases:
Object.prototype.toString.call([]); // [object Array]
Object.prototype.toString.call(new Array()); // [object Array]
Great, no [object Object]
in sight! Sadly, this method still manages to fail with this:
var arr = Object.create(Array.prototype);
Object.prototype.toString.call(arr); // [object Object]
This is frustrating, so say the least. My arr
object has all the methods of an array, it functions like an array, and for all purposes, it is an array. Yet JavaScript doesn't provide the tools to identify it as such.
Is there any way to figure out if an object inherits from a particular prototype? I suppose you could iterate through the prototypes like so:
function inherits(obj, proto) {
while (obj != null) {
if (obj == proto) return true;
obj = Object.getPrototypeOf(obj);
}
return false;
}
inherits(Object.create(Array.prototype), Array.prototype); // true
But it feels a tad hacky. Is there any cleaner approach?