`
tapestry
  • 浏览: 188433 次
社区版块
存档分类
最新评论

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 代码
 
  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<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 代码
 
  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. }  
分享到:
评论

相关推荐

    Java邮件开发Fundamentals of the JavaMail API

    the JavaMail API, if you want this type of information, you have to calculate it yourself. IMAP IMAP is a more advanced protocol for receiving messages. Defined in RFC 2060 , IMAP stands for ...

    Object- Oriented Programming with Ansi-C

    type checking to catch our mistakes earlier on. In chapter nine we arrange for automatic initialization to prevent another class of bugs. Chapter ten introduces delegates and shows how classes and ...

    FlexGraphics_V_1.79_D4-XE10.2_Downloadly.ir

    - FIX: In "Windows ClearType" font rendering mode (OS Windows mode) the "garbage" pixels can appear from the right and from the bottom sides of the painted rectangle of the TFlexText object....

    Google C++ Style Guide(Google C++编程规范)高清PDF

    The definition of an inline function needs to be in a header file, so that the compiler has the definition available for inlining at the call sites. However, implementation code properly belongs in ....

    微软内部资料-SQL性能优化3

    In our example, if one transaction (T1) holds an exclusive lock at the table level, and another transaction (T2) holds an exclusive lock at the row level, each of the transactions believe they have ...

    Streams apple

    Listing 1 in this section outlines a basic strategy for handling stream errors, including checking the status and taking appropriate actions based on the error type. #### Setting Up Socket Streams ...

    [Go语言入门(含源码)] The Way to Go (with source code)

    The Way to Go,: A Thorough Introduction to the Go Programming Language 英文书籍,已Cross the wall,从Google获得书中源代码,分享一下。喜欢请购买正版。 目录如下: Contents Preface......................

    ObjCRuntimeGuide

    - **Message Forwarding:** If an object receives a message that does not match any of its methods, the runtime system can forward the message to another object. This process involves a series of steps,...

    11g_plsql_user_guide_and_reference.pdf

    The `RESET` option for the `ALTER TYPE` statement allows developers to reset an object type to its original state, undoing any changes made since its creation. This feature is useful for testing and ...

    VclZip pro v3.10.1

    If you currently work with VCLZip 2.X with TBlobStreams or some other type of streams, you can either define your own TkpBlobStream for instance which inherits from TkpHugeStream, or use the ...

    JavaScript in 10 Minutes

    12. **Type Checking with `instanceof`**: Discusses the use of `instanceof` for checking the type of an object and its limitations. 13. **Browser Incompatibilities**: Highlights differences in behavior...

    Python Cookbook, 2nd Edition

    Sorting a List of Objects by an Attribute of the Objects Recipe 5.4. Sorting Keys or Indices Basedon the Corresponding Values Recipe 5.5. Sorting Strings with Embedded Numbers Recipe 5.6. ...

    The way to go

    1.2.3 Targets of the language....................................................................................5 1.2.4 Guiding design principles........................................................

    Sakemail

    Fixed a bug when sending email to more than two address (the separator is still ‘,‘).9/3/981.6.0- Sometimes the filenames of an attachment contain invalid chars making very dificult to open a ...

    Collections

    Pointer collection classes can also be configured for arbitrary pointer use, allowing them to hold any type of pointer, including non-object pointers. #### Working with Collections: Copying and ...

    网页制作完全手册

    You should always check for the type and version of the client browser, so that your content degrades gracefully if the client browser does not support features on your Web site. The easiest way to ...

    BobBuilder_app

    I also tried an assorted number of sorting routines like double pivot quick sort, timsort, insertion sort and found that they all were slower than the internal .net quicksort routine in my tests. ...

    VB编程资源大全(英文源码 网络)

    1 , WinLocaleConvert.zip This program shows the international settings of the country you select such as Format Currency, Date Format, Day Name, Month Name...&lt;END&gt;&lt;br&gt;2 , netstuff.zip This ...

    LCTF软件备份VariSpec™ Liquid Crystal Tunable Filters

    With these routines, one can address the filter as a virtual object, with little need for detailed understanding of its behavior. This simplifies the programming task for those who want to integrate ...

Global site tag (gtag.js) - Google Analytics