Typeof returns a string of the expression data type. The returned result is of the basic js data type, including number, boolean, string, object, undefined, and function. the syntax is typeof (data) or typeof data.
Instanceof is used to determine whether an object is of a certain data type or whether a variable is an instance of an object. A boolean type is returned.
The syntax is o instanceof.
The following is a comprehensive example:
Reference content is as follows: <Script type = "text/javascript"> <! - Alert ("typeof (1):" + typeof (1); // number Alert ("typeof (\" abc \ "):" + typeof ("abc"); // string Alert ("typeof (true):" + typeof (true); // boolean Alert ("typeof (2009-2-4):" + typeof (2009-2-4); // number Alert ("typeof (\" 2009-2-4 \ "):" + typeof ("2009-2-4 2-4"); // string Alert ("typeof (m):" + typeof (m); // undefined Var d = new Date (); Alert ("typeof (d):" + typeof (d); // object Function Person (){}; Alert ("typeof (Person):" + typeof (Person); // function Var a = new Array (); Alert ("typeof (a):" + typeof (a); // object Alert ("a instanceof Array:" + (a instanceof Array )); Var h = new Person (); Var o = {}; Alert ("h instanceof Person:" + (h instanceof Person); // true Alert ("h instanceof Object:" + (h instanceof Object); // true Alert ("o instanceof Object:" + (o instanceof Object); // true Alert (typeof (h); // object //-> </Script> |
In js, constructor is rarely used. If not relevant information about construtor is found, I have never noticed that js still has this function. A bad thing about typeof is that it returns both Array and user-defined functions as objects.
Reference content is as follows: <Script type = "text/javascript"> <! - Var j = 2; Alert (typeof (j); // number Alert ("j. constructor:" + j. constructor); // function... Alert (typeof (j. constructor); // function //-> </Script> |
You can see the js. constructor returns some strings. You can see that this is a function type. In this example, Number () is the constructor of the Number object, Number () it is used to convert its parameters to the number type and return the Conversion Result (if it cannot be converted, NaN is returned ).
Therefore, you can use the following method to obtain the detailed data type for future js data types.
Reference content is as follows: If (typeof o = "object") & (o. constructor = Number )){ ... } |
Note that constructor can only judge existing variables, while typeof can judge undefined variables ).