The way of checking the type of an object
Apress ProJavaScriptTechniques
The first way of checking the type of an object is by using the obvious-sounding typeof operator.
js 代码
- // Check to see if our number is actually a string
- if ( typeof num == "string" )
- // If it is, then parse a number out of it
- num = parseInt( num );
- // Check to see if our array is actually a string
- if ( typeof arr == "string" )
- // If that's the case, make an array, splitting on commas
- arr = arr.split(",");
The second way of checking the type of an object is by referencing a property of all JavaScript objects called constructor.
js 代码
- // Check to see if our number is actually a string
- if ( num.constructor == String )
- // If it is, then parse a number out of it
- num = parseInt( num );
- // Check to see if our string is actually an array
- if ( str.constructor == Array )
- // If that's the case, make a string by joining the array using commas
- str = str.join(',');
Table 2-1 shows the results of type-checking different object types using the two different methods that I’ve described.
Variable<o:p></o:p>
typeof Variable<o:p></o:p>
Variable.constructor<o:p></o:p>
{ an: “object” }<o:p></o:p>
object<o:p></o:p>
Object<o:p></o:p>
[ “an”, “array” ]<o:p></o:p>
array<o:p></o:p>
Array<o:p></o:p>
function(){}<o:p></o:p>
function<o:p></o:p>
Function<o:p></o:p>
“a string”<o:p></o:p>
string<o:p></o:p>
String<o:p></o:p>
55<o:p></o:p>
number<o:p></o:p>
Number<o:p></o:p>
true<o:p></o:p>
boolean<o:p></o:p>
Boolean<o:p></o:p>
new User()<o:p></o:p>
object<o:p></o:p>
User<o:p></o:p>
Strict typechecking can help in instances where you want to make sure that exactly the right number of arguments of exactly the right type are being passed into your functions.
js 代码
- // Strictly check a list of variable types against a list of arguments
- function strict( types, args ) {
- // Make sure that the number of types and args matches
- if ( types.length != args.length ) {// If they do not, throw a useful exception
- throw "Invalid number of arguments. Expected " + types.length +
- ", received " + args.length + " instead.";
- }
- // Go through each of the arguments and check their types
- for ( var i = 0; i < args.length; i++ ) {
- //
- if ( args[i].constructor != types[i] ) {
- throw "Invalid argument type. Expected " + types[i].name +
- ", received " + args[i].constructor.name + " instead.";
- }
- }
- }
- // A simple function for printing out a list of users
- function userList( prefix, num, users ) {
- // Make sure that the prefix is a string, num is a number,
- // and users is an array
- strict( [ String, Number, Array ], arguments );
- // Iterate up to 'num' users
- for ( var i = 0; i < num; i++ ) {
- // Displaying a message about each user
- print( prefix + ": " + users[i] );
- }
- }