Hacker News new | ask | show | jobs
by mkmcdonald 5174 days ago
Your API will explode violently in IE < 8 || Quirks. This is because of gratuitous use of `setAttribute` along with `Array.prototype.slice.call` (dirty hack)[0]. IE < 8 || Quirks already treats HTML attributes and DOM properties identically[1], so really, DOM properties are preferred. More standards-compliant environments will reflect the property value in the corresponding attribute value (if possible).

Using `Object.prototype.toString.call` is also a pretty dirty hack, especially to detect an "array". I think `typeof obj === "object" && obj.length` would suffice, even if certain false positives like string objects leak through.

[0]: http://i.imgur.com/RNBYd.png

[1]: http://msdn.microsoft.com/en-us/library/dd347148(v=VS.85).as...

1 comments

The "Object.prototype.toString.call" solution is guaranteed to work according to ECMA-262, and will only return true for a real Array instance (not something masquerading as an Array):

Object.prototype.toString ( ) When the toString method is called, the following steps are taken:

1. If the this value is undefined, return "[object Undefined]".

2. If the this value is null, return "[object Null]".

3. Let O be the result of calling ToObject passing the this value as the argument.

4. Let class be the value of the [[Class]] internal property of O.

5. Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".

That may be, but it's poison for host objects. In older IE and Opera builds, `"[object Object]"` comes up often, even for host methods.

This is because there is no defined standard for `toString` results of host objects.