jQuery uses a clever bit of code to extract the type of a parameter.
However, this often returns unexpected results:
jQuery solved this problem by applying the Object.prototype.toString method which returns
more predictable results–albeit in a strange format:
However, this technique will not work with your home-grown types (Classes). For instance:
You probably expected to see “[object X]”.
Well, there’s another Object.prototype method called toLocaleString.
It’s best known as a way to localize date objects. However, as the MDC points out
it returns toString, so it can work on any object that has that method.
One more hurdle to overcome–just using toLocaleString will cause normal objects to
return their string values instead of a type string:
By using toLocaleString only for “[object Object]” results, we can create a more
convenient type method and get the expected results. I will also take the time to fix
null, undefined, and NaN. Using a simple memoizer, I will collect and return the
constructor in lower case like jQuery does:
Chrome reports Arguments as “[object Arguments]”, which you may think incredibly useful.
However, other browsers return [object Object] and there remains no easy way to differentiate
arguments from non-arguments objects. So, I recommend adding another case at the end of
the switch statement above: