I know that we can detect a variable's type in Javascript like this:
Object.prototype.toString.call([]); // [object Array]
Object.prototype.toString.call({}); // [object Object]
Object.prototype.toString.call(''); // [object String]
Object.prototype.toString.call(new Date()); // [object Date]
Object.prototype.toString.call(1); // [object Number]
Object.prototype.toString.call(function () {}); // [object Function]
Object.prototype.toString.call(/test/i); // [object RegExp]
Object.prototype.toString.call(true); // [object Boolean]
Object.prototype.toString.call(null); // [object Null]
Object.prototype.toString.call(); // [object Undefined]
But why?
How are these values ([object Array], [object String]...) returned, and what does Object.prototype.toString do?
Object.prototype.toString basically returns the [[Class]] (implementation detail) internal property of the objects. Quoting the section from ECMA Script 5.1 specification, where this is defined
- If the
thisvalue isundefined, return"[object Undefined]".- If the
thisvalue isnull, return"[object Null]".- Let O be the result of calling
ToObjectpassing thethisvalue as the argument.- Let class be the value of the
[[Class]]internal property of O.- Return the String value that is the result of concatenating the three Strings
"[object ",class, and"]".
Also,
The value of the
[[Class]]internal property is defined by this specification for every kind of built-in object. The value of the[[Class]]internal property of a host object may be any String value except one of"Arguments","Array","Boolean","Date","Error","Function","JSON","Math","Number","Object","RegExp", and"String". The value of a[[Class]]internal property is used internally to distinguish different kinds of objects. Note that this specification does not provide any means for a program to access that value except throughObject.prototype.toString.
So, Object.prototype.toString is the only function which can access the [[Class]] property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With