alt
Advertisement
Online Training
Career Series
Exforsys
Exforsys arrow Tutorials arrow Microsoft AJAX arrow Microsoft AJAX Library - JavaScript Classes
Site Search


Microsoft AJAX Library - JavaScript Classes
Article Index
Microsoft AJAX Library - JavaScript Classes
Create New Class Instance
JavaScript Class Diagrams

Create New Class Instance

Once your new class is created, you use it just as you'd use a C# class. For example, this is how you'd create a new class instance, and call its DisplayGreeting() method:

  1. // create class instance
  2.  
  3. var myHello = new HelloWorld();
  4.  
  5. // call method
  6.  
  7. myHello.DisplayGreeting();
 

A possible implementation of the HelloWorld class is the following:

  1. // "Hello, World" class
  2.  
  3. function HelloWorld(hour)
  4.  
  5. {
  6.  
  7. // class "constructor" initializes this.hour field
  8.  
  9. if (hour)
  10.  
  11. {
  12.  
  13. // if the hour parameter has a value, store it as a class field
  14.  
  15. this.hour = hour;
  16.  
  17. }
  18.  
  19. else
  20.  
  21. {
  22.  
  23. // if the hour parameter doesn't exist, save the current hour
  24.  
  25. var date = new Date();
  26.  
  27. this.hour = date.getHours();
  28.  
  29. }
  30.  
  31. // display greeting
  32.  
  33. this.DisplayGreeting = function()
  34.  
  35. {
  36.  
  37. if (this.hour >= 22 || this.hour <= 5)
  38.  
  39. document.write("Goodnight, world!");
  40.  
  41. else
  42.  
  43. document.write("Hello, world!");
  44.  
  45. }
  46.  
  47. }
 

This code can be tested online at http://www.cristiandarie.ro/asp-ajax/ JavaScriptClass.html. The HelloWorld class is formed of the constructor code that initializes the hour field (this.hour), and of the DisplayGreeting() method—this.DisplayGreeting(). Fans of the ternary operator can rewrite the constructor using this shorter form, which also makes use of the object detection feature that was discussed in Chapter 2:

  1. // define and initialize this.hour
  2.  
  3. this.hour = (hour) ? hour : (new Date()).getHours();
 


NOTE: The ternary operator is supported both by C# and JavaScript. It has the form (condition ? valueA : valueB). If the condition is true, the expression returns valueA, otherwise it returns valueB. In the shown example, object detection is used to test if a value was supplied for the hour parameter. If it was not, the current hour is used instead.



 
< Prev   Next >
Sponsored Links
© 2008 Exforsys.com
Joomla! is Free Software released under the GNU/GPL License.
Page copy protected against web site content infringement by Copyscape