Creating Objects in JavaScript

As we already know, JavaScript comes with a number of built-in objects ready for you to use, such as the document , location , navigator , and history objects. JavaScript also comes with many classes built in, including classes such as the Date class, which handles dates and times, and the Math class, which has many built-in methods such as min and max to compare numbers . You can use built-in classes (and those you create yourself, although we're not going to do that here) to create objects using the new operator.

You can think of a class as an object's type because, using the new operator, you create objects from classes. Objects can have methods and properties built into themin fact, most do. We'll be using the new operator in the next chapter to create objects that will let us handle XML documents. We've already seen new at work in this chapter in this example:

 <HTML>      <HEAD>         <TITLE>             Using JavaScript Functions         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>                 Using JavaScript Functions             </H1>         </CENTER>         <SCRIPT LANGUAGE = "JavaScript">             document.writeln("The time is " + getTime()             + " right now.")             function getTime()             {  var now = new Date  var returnValue = now.getHours() + ":"                 + now.getMinutes()                 return(returnValue)             }         </SCRIPT>     </BODY> </HTML> 

The new operator uses the Date class's constructor, which is a special method that classes use to create and return objects. In this case, we didn't pass any arguments to the Date class's constructor, so the object that it returns and that we call now here will reflect the current date. On the other hand, you could pass a date to the Date class's constructor when you use the new operator, and the Date object returned will reflect that date instead. Here's what that might look like:

 var then = new Date("10/15/2001") 

Class Affects Value Types

How do you know what kind of values you can pass to a JavaScript class's constructor? Take a look at the JavaScript documentation; what arguments, and what order you pass them in, varies by class.

One important class that's built into JavaScript is the String class, which you use to handle text strings. To get a better idea of how classes, objects, and constructors work, I'll take a look at that class next.



Real World XML
Real World XML (2nd Edition)
ISBN: 0735712867
EAN: 2147483647
Year: 2005
Pages: 440
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net