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

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....

    [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......................

    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 ...

    Joomla! 1.5 Development Cookbook.pdf

    Managing categories the easy way 243 Defining JParameters using XML 245 Creating a JParameter object 247 Rendering a JParameter object 248 Saving JParameter data 251 Getting and setting values in...

    Python Cookbook英文版

    2.6 Sorting a List of Objects by an Attribute of the Objects 2.7 Sorting by Item or by Attribute 2.8 Selecting Random Elements from a List Without Repetition 2.9 Performing Frequent Membership ...

    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 ...

    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 ...

    Fsharp Succinctly(Syncfusion,2012)

    imperative, and object-oriented styles in the same program and exploit the strengths of each paradigm. Like other typed functional languages, F# is strongly typed but also uses inferred typing so ...

    网页制作完全手册

    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 ...

    JavaScript Applications with Node.js, React, React Native and MongoDB

    This book will teach you how to develop JavaScript applications with simple to use, yet powerful JavaScript technologies and host everything in the cloud in an economic and robust way in AWS. Enjoy an...

    ICS delphixe10源码版

    The latest versions of ICS can be downloaded from the ICS Wiki web site: http://wiki.overbyte.be/wiki/index.php/ICS_Download ICS V5 and V6 are archive releases no longer updated, last supported ...

    Tricks of the Windows video Game Programming---part1

    Tricks of the Windows video Game Programming &lt;br&gt;PART I Windows Programming Foundations 7 1 Journey into the Abyss 9 A Little History.............................................................

Global site tag (gtag.js) - Google Analytics