In Douglas Crockford's book "JavaScript: The Good Parts", he used a complex function as below:
var is_array = function (value) {
return value &&
typeof value === 'object' &&
typeof value.length === 'number' &&
typeof value.splice === 'function' &&
!(value.propertyIsEnumerable('length'));
};
In one of his recent blog posts, he mentioned that Mark Miller from Google used a simple approach to do the same thing.
Object.prototype.toString.apply(value) === '[object Array]'
I went through the ECMAScript specification and found out the following:
The value of the [[Class]] property is defined by this specification for every kind of built-in object. The value of the [[Class]] property of a host object may be any value, even a value used by a built-in object for its [[Class]] property. The value of a [[Class]] property is used internally to distinguish different kinds of built-in objects. Note that this specification does not provide any means for a program to access that value except through Object.prototype.toString.
The [[Class]] property of Array.prototype is "Array" and Object.prototype.toString uses this value to generate the output in the format "[object " + [[Class]] + "]" which results "[object Array]".
I think the new approach can help us a lot.
没有评论:
发表评论