I have been trying to find a better way to check data types in JavaScript. I know there are typeof
and instanceof
operators but they all have some pitfalls. And I found there is a method toString
on Object.prototype
can solve this very elegantly because it can differentiate all of the types by returning different strings based on Symbol.toStringTag
Object.prototype.toString.call(function(){}) // "[object Function]"
Object.prototype.toString.call(null) //"[object Null]"
Object.prototype.toString.call(undefined) //"[object Undefined]"
Object.prototype.toString.call(/123/g) //"[object RegExp]"
Object.prototype.toString.call(new Date()) //"[object Date]"
Object.prototype.toString.call([]) //"[object Array]"
And it also works on primitive types.
However one thing I don't quite understand is that if we leave out .call
from Object.prototype.toString
and we just invoke it as in Object.prototype.toString()
it returns [object Object]
for everything.
So my question is what is it that makes .call
result in correct strings for types?
question from:
https://stackoverflow.com/questions/65874903/javascript-differences-between-object-prototype-tostring-callfoo-and-objec 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…