Javascript is weakly typed, and its type system always behaves different than your expectation.
Javascript provide typeof operator to test the type of a variable. it works fine generally. e.g.
|
|
But it is not enough, it behaves stupid when you dealing with objects created by constructors. e.g.
if you expected
Then you must be disappointed, since actually
Yes, when you apply typeof()
operator on any objects, it just yield the general type “object” rather than the more meaningful type “date”.
How can we make the typeof()
operator works in the way as we expected?
As we know when we create a object, the special property of the object constructor will be set to the function that create the object. which means:
|
|
So ideally we can retrieve the name of the function as the type of the variable. And to be compatible with javascript’s native operator, we need to convert the name to lower case. So we got this expression:
|
|
And luckily, we can also apply this to other primitive types, e.g:
|
|
or even
|
|
So in general, we use this expression as new implementation of the typeof()
operator! EXCEPT One case!
If someone declare the object constructor in this way, our new typeof()
implementation will work improperly!
|
|
or even define the constructor like this
|
|
And we will find that
|
|
the reason behind this is because the real constructor of the SomeClass is actually an anonymous function, whose name is not set.
To solve this problem, we need to declare the name of the constructor:
|
|
or even define the constructor like this
|
|