Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can Object.prototype.toString.call(foo) detect foo's type?

Tags:

javascript

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?

like image 656
Miaonster Avatar asked Feb 01 '26 16:02

Miaonster


1 Answers

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

  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 "]".

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 through Object.prototype.toString.

So, Object.prototype.toString is the only function which can access the [[Class]] property.

like image 162
thefourtheye Avatar answered Feb 04 '26 04:02

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!