Exforsys.com
 
Home Tutorials Microsoft AJAX
 

Microsoft AJAX Library - JavaScript Classes

 

Create New Class Instance

Page 2 of 3


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:



Sample Code
  1. // create class instance
  2. var myHello = new HelloWorld()
  3. // call method
  4. myHello.DisplayGreeting()
Copyright exforsys.com



A possible implementation of the HelloWorld class is the following:


Sample Code
  1. // "Hello, World" class
  2. function HelloWorld(hour)
  3. {
  4. // class "constructor" initializes this.hour field
  5. if (hour)
  6. {
  7. // if the hour parameter has a value, store it as a class field
  8. this.hour = hour
  9. }
  10. else
  11. {
  12. // if the hour parameter doesn't exist, save the current hour
  13. var date = new Date()
  14. this.hour = date.getHours()
  15. }
  16. // display greeting
  17. this.DisplayGreeting = function()
  18. {
  19. if (this.hour >= 22 this.hour <= 5)
  20. document.write("Goodnight, world!")
  21. else
  22. document.write("Hello, world!")
  23. }
  24. }
Copyright exforsys.com



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:


Sample Code
  1. // define and initialize this.hour
  2. this.hour = (hour) ? hour : (new Date()).getHours()
Copyright exforsys.com





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.




Next Page: JavaScript Class Diagrams


Read Next: Microsoft AJAX Library - C# and JavaScript Classes



 

 

Comments



Post Your Comment:

Members Please Login
Your Name:*
e-mail ID:(required for notification)*
Image Verification: 
 
 Subscribe    

Sponsored Links

 

Subscribe via RSS


Get Daily Updates via Subscribe to Exforsys Free Training via email


Get Latest Free Training Updates delivered directly to your Inbox...

Enter your email address:


 

Subscribe to Exforsys Free Training via RSS
 

 
Partners -  Privacy and Legal Policy -  Site News -  Contact   Sitemap  

Copyright © 2000 - 2009 exforsys.com. All Rights Reserved

Page copy protected against web site content infringement by Copyscape