2006-12-28

The way of checking the type of an object

关键字: javascript

Apress ProJavaScriptTechniques

The first way of checking the type of an object is by using the obvious-sounding typeof operator.

js 代码
 
  1. // Check to see if our number is actually a string  
  2. if ( typeof num == "string" )  
  3. // If it is, then parse a number out of it  
  4. num = parseInt( num );  
  5. // Check to see if our array is actually a string  
  6. if ( typeof arr == "string" )  
  7. // If that's the case, make an array, splitting on commas  
  8. 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 代码
 
  1. // Check to see if our number is actually a string  
  2. if ( num.constructor == String )  
  3. // If it is, then parse a number out of it  
  4. num = parseInt( num );  
  5. // Check to see if our string is actually an array  
  6. if ( str.constructor == Array )  
  7. // If that's the case, make a string by joining the array using commas  
  8. 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

typeof Variable

Variable.constructor

{ an: “object” }

object

 Object

[ “an”, “array” ]

array

Array

function(){}

function

Function

“a string”

string

String

55

number

Number

true

boolean

Boolean

new User()

object

User


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 代码
 
  1. // Strictly check a list of variable types against a list of arguments  
  2. function strict( types, args ) {  
  3. // Make sure that the number of types and args matches  
  4. if ( types.length != args.length ) {// If they do not, throw a useful exception  
  5. throw "Invalid number of arguments. Expected " + types.length +  
  6. ", received " + args.length + " instead.";  
  7. }  
  8. // Go through each of the arguments and check their types  
  9. for ( var i = 0; i < args.length; i++ ) {  
  10. //  
  11. if ( args[i].constructor != types[i] ) {  
  12. throw "Invalid argument type. Expected " + types[i].name +  
  13. ", received " + args[i].constructor.name + " instead.";  
  14. }  
  15. }  
  16. }  
  17. // A simple function for printing out a list of users  
  18. function userList( prefix, num, users ) {  
  19. // Make sure that the prefix is a string, num is a number,  
  20. // and users is an array  
  21. strict( [ String, Number, Array ], arguments );  
  22. // Iterate up to 'num' users  
  23. for ( var i = 0; i < num; i++ ) {  
  24. // Displaying a message about each user  
  25. print( prefix + ": " + users[i] );  
  26. }  
  27. }  
评论
发表评论

您还没有登录,请登录后发表评论

tapestry
搜索本博客
最近加入圈子
存档
最新评论