- Object
- String
- Number
- Date
- Function
- ...
var mynmbr = new Number(1); var mystrng = new String("disasterjs!"); var myfunc = function(){ console.log("hello world!"); } mynmbr instanceof Number //returns true mynmbr instanceof Object //returns true mystrng instanceof String //returns true mystrng instanceof Object //returns true mynmbr instanceof String //returns false myfunc instanceof Function //returns true
Be careful when using instanceof about what you are checking. For example numbers and strings not wrapped in the constructor are treated as primitive value, thus a call for instanceof in that case would produce an unexpected result:
var mystrng = "disasterjs!"; var mynmbr = 1; mynmbr instanceof Number //returns false mynmbr instanceof Object //returns false mystrng instanceof String //returns false mystrng instanceof Object //returns false
What about the typeof operator? This operator returns the class as a string. The following table summarises its possible return values:
Type
|
Result
|
---|---|
Undefined | "undefined" |
Null | "object" |
Boolean | "boolean" |
Number | "number" |
String | "string" |
Host object (provided by the JS environment) | Implementation-dependent |
Function | "function" |
E4X XML object | "xml" |
Any other object | "object" |
Programmer may be careful here when checking a Null object as the result of a typeof will return "object". Here are a couple of examples on how to use typeof.
typeof 1 === "number" //true typeof Number(1) === "number" //true typeof 1 === "object" //false typeof undefined_variable === "undefined" //true typeof true === "boolean" //true
And that's it.
0 comments:
Post a Comment