Reputation:
I've regularly used toString() for two different ways, but only recently I realized I don't understand the mechanics of what is going on.
For example I use this function to return the type of an object:
var getType = function (obj) {
return Object.prototype.toString.call(obj).slice(8, -1);
};
getType([1,2,3]) // returns "Array"
But if I do
[1,2,3].toString()
I will get
"1,2,3"
I thought that call
simply calls the function with a given this
which is equal to [1,2,3]
.
Similarly I thought that doing [1,2,3].toString()
calls toString with [1,2,3]
as the this
value as well.
In both cases there are no parameters and the this
value is the same so what is different?
Upvotes: 0
Views: 90
Reputation: 288710
That's because
Array.prototype.toString !== Object.prototype.toString
For example:
Array.prototype.toString.call([1,2,3]); // "1,2,3"
Object.prototype.toString.call([1,2,3]); // "[object Array]"
Upvotes: 5