The ToString () method is a method that all objects have, whether it is a string, an array, an object, can call this method, but, in fact, they are not calling the same function Oh! Look at the following code:
var str = ' 123 '; Console.log (Object.prototype.toString= = =str.tostring); //false
Console.log (string.prototype.tostring===str.tostring); //true
Console.log (Object.prototype.toString.call (str)); //' [Object String] 'console.log (str.tostring ()); //' 123 '
As you can see, the str.tostring here is called the String.protype.toString method, not the Object.prototype.toString method
Let's look at the following code:
var arr = [];console.log (Object.prototype.toString===arr.tostring); // false
Console.log (array.prototype.tostring===arr.tostring); //true
Console.log (Object.prototype.toString.call (arr)); // ' [Object Array] 'console.log (arr.tostring ()); //' a '
As you can see, the arr.tostring here is called the Array.prototype.toString method, not the Object.prototype.toString method
var obj = {name: ' Bunny '};console.log (Object.prototype.toString===obj.tostring); // trueconsole.log (Object.prototype.toString.call (obj)); // ' [Object Object] 'console.log (obj.tostring ()); // ' [Object Object] '
As you can see, for obj, the ToString method that it calls is the Object.prototype.toString method.
Similarly, numeric types, as well as functions, are similar to this ... No longer an example ...
Additionally, NULL does not have the ToString method:
var NULL ; Console.log (nu.tostring); // Error
But it can call the other ToString methods:
var nu=null; Object.prototype.toString.call (nu) //' [Object null] '
So we can know that in the prototype of array, the prototype of string, and the prototype of number, the prototype of the function, there are its own ToString method, different types of objects, will call the different ToString method, Instead of calling Object.prototype.toString.
At that time, we could call the Object.prototype.toString function by calling function, in this way, we can get the object type precisely:
' [Object Object] '
' [Object Array] '
' [Object String] '
' [Object number] '
' [Object Function] '
' [Object Undefined] '
' [Object Null] '
For example, a function that determines whether an object is an array:
if (array.isarray===undefined) { function(obj) { return Object.prototype.toString.call (obj) = = = ' [Object Array] ' } }
JavaScript's tostring in-depth exploration