The toString method inherited from Object.prototype serves as a reliable means for type detection in JavaScript, particularly useful for differentiating between arrays and plain objects.
Consider the following examples:
Object.prototype.toString.call(''); //[object String]
Object.prototype.toString.call(1); //[object Number]
Object.prototype.toString.call(true); //[object Boolean]
Object.prototype.toString.call([]); //[object Array]
Object.prototype.toString.call({}); //[object Object]
Object.prototype.toString.call(undefined); //[object Undefined]
Object.prototype.toString.call(null); //[object Null]
Object.prototype.toString.call(new Function()); //[object Function]
Object.prototype.toString.call(new Date()); //[object Date]
Object.prototype.toString.call(new RegExp()); //[object RegExp]
Object.prototype.toString.call(new Error()); //[object Error]
Object.prototype.toString.call(document); //[object HTMLDocument]
document.toString(); //[object HTMLDocument]
Object.prototype.toString.call(window); //[object Window]
window.toString(); //[object Window]
// Invoking toString through the prototype chain achieves the same result
toString.call([]); //[object Array]
A question arises: why can't Object.toString be used to invoke the toString method from the prototype chain?
While all objects ultimately inherit from Object.prototype, Object itself is also a constructor function that inherits from Function. Therefore, calling Object.toString traverses the prototype chain to reach Function.prototype.toString. The relationships are as follows:
Object.prototype.__proto__ === null; // true
Function.prototype.__proto__ === Object.prototype; // true
Object.toString === Function.prototype.toString; // true
Native Object Constructor toString Methods
Built-in constructors such as Number, String, Boolean, Array, RegExp, Date, and Function override the toString method inherited from Object.prototype. These implementations convert their respective data types into string representations.
Number.toString(); // "function Number() { [native code] }"
String.toString(); // "function String() { [native code] }"
Boolean.toString(); // "function Boolean() { [native code] }"
Array.toString(); // "function Array() { [native code] }"
RegExp.toString(); // "function RegExp() { [native code] }"
Date.toString(); // "function Date() { [native code] }"
Function.toString(); // "function Function() { [native code] }"