Previous: Controlling Your JavaScript | Next: Summary |
So far in this chapter, you've been introduced quickly to creating scripts that perform logical computing tasks using JavaScript. In this last section, we'll be focusing on JavaScript's use of objects or collections of properties.
JavaScript, as with many other modern-day computer languages, is object-oriented. This means you can create these special named collections of properties that include variables and special built-in functions, called methods. You'll find that these objects can make working with chunks of data quite a bit easier.
In more practical terms, an object is a named container of sorts. In most cases, you create an object with a special function, in a way that's similar to creating an array. You can then refer to the object using special notation that enables you to dig into the object and access certain variables or methods. You've already seen a few instances of this, such as
document.writeln()
This command is actually a call to the writeln() method that is part of the document object. As you'll see in "Adding Dynamic HTML Elements" (also available online), an HTML document is actually one large object with many different variables that you can access and change. Changing aspects of the document is one of the really cool things that JavaScript enables you to do.
You can also create your own objects and use them to store values. As an example, consider an object called home01. This particular object is designed to store information about a real estate listing, so it might have the following variables as part of it:
home01.price = 125000 home01.sqfoot = 2300 home01.beds = 3 home01.baths = 2 home01.base = true home01.descrip = "Great location, good schools."
What's happened here is simplevalues have been assigned to variables that all happen to be associated with one another, because they're all properties of the home01 object. Because they're all part of a single object, you can use the object for such things as function calls:
<script> showListing (home01); </script>
And then you can use the pointer to that object to access each of the individual variables:
<script> function showListing (home) { document.writeln ("Home Price = " + home.price + "<br \/>">); document.writeln ("Square Footage = " + home.sqfoot + "<br \/>"); document.writeln ("Beds/Baths = " + home.beds + "/" + home.baths + "<br \/>"); document.writeln ("Description = " + home.descrip + "<br \/>"); return; } </script>
Of course, for this example to work correctly, you'd need to actually create the object home01, which I haven't gotten around to telling you how to do yet. Let's look at how that's done before moving on.
Creating objects is done in two steps. First, you need to create a template for the object, which is done using a function declaration. Then, you need to create an instance of a particular object so that you can begin to work with it.
For instance, to create the template for your home object, you need to create a function:
function home(price, sqfoot, beds, baths, base, descrip) { this.price = price; this.sqfoot = sqfoot; this.beds = beds; this.baths = baths; this.base = base; this.descrip = descrip; }
Notice the use of the word this. In JavaScript, this is a special keyword that's used to refer to the current object. It's used throughout object manipulation, particularly with forms, as you see in "JavaScript and User Input".
Meanwhile, note also that the object will be created, based on the function template, using the new keyword. Using new is the second step in creating your new object. The following is an example:
home01 = new home(125000, 2300, 3, 2, true, "Great location, good schools.") ;
The new keyword creates a new object. It also tells the object-creating home function that the price of this new object will be 125000, and so on. When the home function is called, home01 will replace this and the assignment will work like this:
home01.price = 125000 home01.sqfoot = 2300 home01.beds = 3 home01.baths = 2 home01.base = true home01.descrip = "Great location, good schools."
Of course, you won't see any of this happen. But, it's now possible for you to access this data just like a regular object:
document.writeln ("This house is priced at: $" + home01.price);
What if you only want to create one object? If that's the case, you don't need a template. Instead, you can simply use an assignment to create the object:
myhouse = {price:125000, sqfoot:2300, beds:3, baths:2, base:true, descrip:"Great location, good schools."}
And while you're working with individual objects, you're free to add properties to an object at any time. For instance:
home01.location = "midtown"
This is perfectly okay. It won't affect any other objects that have been created, even if those objects used the same function template that this one did.
Just as an object's properties are simply variables that are associated with that object, methods are basically functions associated with objects. For instance, one of the methods you've used quite a bit is document.writeln(), which is really just a function provided by JavaScript that allows you to write XHTML marked-up text to the current document object.
Notice that writeln() is the function, and document is the associated object. JavaScript-compatible browsers define certain basic objects, like document, so it's easier to access them and change their properties.
You can even create your own methods by simply assigning a function name to an object variable:
object.methodname = function_name
Or, in an object definition function, you can create a method like this:
function showListing () { document.writeln ("Home Price = " + this.price + "<br \/>">); document.writeln ("Square Footage = " + this.sqfoot + "<br \/>"); document.writeln ("Beds/Baths = " + this.beds + "/" + this.baths + "<br \/>"); document.writeln ("Description = " + this.descrip + "<br \/>"); return; } function home(price, sqfoot, beds, baths, base, descrip) { this.price = price; this.sqfoot = sqfoot; this.beds = beds; this.baths = baths; this.base = base; this.descrip = descrip; this.showListing = showListing;
}
Then, for instance, if you've defined an object named home01, calling the method home01.showListing() would cause the showListing function to execute, using home01 in the place of the this keyword in the function.
NOTE
Note that you need to include the parentheses when you're calling methods, even if you don't have data to pass to that method. If that's the case, just opened and closed parentheses "()" are appropriate.
When you're authoring scripts, there are a number of things you're likely to do over and over again. JavaScript includes some of these often-used calls in the language itself, instead of forcing you to write your own functions and create your own objects. The built-in objects tend to store useful values or offer convenient methods. The functions usually perform some fairly intensive calculating that you'll often need to use.
You'll learn about three major built-in objects available for you in JavaScript:
The first is the String object, which helps you manipulate your strings.
The Math object holds certain constant values for you to use in your script and methods, making it a little easier to perform some mathematical functions.
The Date object can be used to get the current date or to create a date object for any date or time in the past or future.
NOTE
These are only a few of the built-in objects, shown here because they're often used and they're representative of the other objects. For more on built-in objects, see the Objects chapter of the JavaScript reference at http://developer.netscape.com/docs/manuals/js/client/jsguide/obj.htm.
The string object is interesting if only because you don't actually have to use the notation string.property to use it. In fact, any string you create is a string object. You can create a string as simple as this:
mystring = "Here's a string"
The string variable mystring can now be treated as a string object. For instance, to get a value for the length of a string object, you can use the following assignment:
stringlen = mystring.length
When you create a string, and JavaScript makes it a string object, the value of its length is stored in the property length. (Note also that, because length is a property and not a method, you don't need the parentheses.) It also associates certain methods with the object, like toUpperCase(). You could change a string to all uppercase letters with the following line:
mystring = mystring.toUpperCase()
If the string had the value "Here is a string", this assignment would change it to "HERE IS A STRING". Table 2 shows some of the other methods available with string objects.
Method |
What It Does |
Example |
anchor |
Creates a target anchor |
mystring.anchor(section_name) |
big |
Displays string as big text |
mystring.big() |
blink |
Displays string as blinking text |
mystring.blink() |
bold |
Displays string as bold text |
mystring.bold() |
charAt |
Selects an individual character |
mystring.charAt(2) |
fixed |
Displays string in teletype font |
mystring.fixed() |
fontcolor |
Displays string in color |
mystring.fontcolor("red") |
fontsize |
Displays string in new font size |
mystring.fontsize(2) |
indexOf |
Finds index # of a letter |
mystring.indexOf("w") |
italics |
Displays string as italic |
mystring.italics() |
lastIndexOf |
Finds last occurrence of letter |
mystring.lastIndexOf("w") |
link |
Creates a link from the string |
mystring.link() |
small |
Displays string as small text |
mystring.small() |
strike |
Displays string as strikethrough text |
mystring.strike() |
sub |
Displays string as a subscript |
mystring.sub() |
substring |
Selects part of the string |
mystring.substring(0,7) |
sup |
Displays string as a superscript |
mystring.sup() |
toLowerCase |
Displays string as lowercase |
mystring.toLowerCase() |
toUpperCase |
Displays string as uppercase |
mystring.toUpperCase() |
You'll notice that the table often says that the string is displayed as something, because the methods don't actually change the original value of the string. Instead, they return a value that's appropriate to their functions. That is, the small() method returns the string as small text, while the toUpperCase() method returns the string as uppercase text. So, the following example doesn't really accomplish anything because the small() method doesn't change the original string:
<script type="text/javascript"> <!-- hide scripting var testString = "Testing 1, 2, 3"; document.writeln (testString + "<br\/>"); testString.small() document.writeln (testString + "<br\/>"); // end hiding --> </script>
A better way to do this would be as follows:
<script type="text/javascript"> <!-- hide scripting var testString = "Testing 1, 2, 3"; document.writeln (testString + "<br\/>"); var upperString = testString.small() document.writeln (upperString + "<br\/>"); // end hiding --> </script>
Now, with the returned value assigned to a new variable, you'll find yourself with something a bit more useful.
So what are these methods doing? For instance, the following two script lines would have the same results:
document.write("<big>" + mystring + "</big>"); document.write(mystring.big());
Some of the other tags need explainingespecially those that deal with indexes. Every string is indexed from left to right, starting with the value 0. So, in the following string (which has been assigned to the variable howdystring), the characters are indexed according to the numbers that appear under them:
Howdy, you 0123456789
In this case, using the method howdystring.charAt(4) would return the value y. You could also use the method howdystring.indexOf("y"), which would return the value 4. Notice that there are two instances of y, however. Using howdystring.lastIndexOf("y"), you could find out that the index of that second y (as it's also the last one in the string) is 7.
The Math object just holds some useful constants and methods for use in mathematical calculations. Its properties are mathematical constants like e, Pi, and log10e (logarithm, base 10, of e). You can use these by simply adding the name as the MMath property, as in the following example:
var pi_value = Math.PI; area = Math.PI*(r*r);
Table 3 shows you the various properties for the Math object.
Property |
Value |
PI |
Pi (approximately 3.1416) |
E |
e, Euler's constant (approximately 2.718) |
LN2 |
Natural log of 2 (approximately 0.693) |
LN10 |
Natural log of 10 (approximately 2.302) |
LOG10E |
Base 10 log of e (approximately 0.434) |
SQRT1_2 |
Square root of 1/2 (approximately 0.707) |
SQRT2 |
Square root of 2 (approximately 1.414) |
Of course, the properties are simply values that are conveniently stored within the Math object. Along with those properties, the Math object offers methods that you can use for a variety of mathematical hoop-jumping. The Math object's methods are called like any other methods. For instance, the arc sine of a variable can be found by using the following:
Math.asin(your_num);
Table 4 shows the methods for the Math object.
Method |
Result |
Format |
abs |
Absolute value |
Math.abs(number) |
acos |
Arc cosine (in radians) |
Math.acos(number) |
asin |
Arc sine (in radians) |
Math.asin(number) |
atan |
Arc tangent (in rads) |
Math.atan(number) |
cos |
Cosine |
Math.cos(num_radians) |
sin |
Sine |
Math.sin(num_radians) |
tan |
Tangent |
Math.tan(num_radians) |
ceil |
Least integer >= num |
Math.ceil(number) |
floor |
Greatest int <= number |
Math.floor(number) |
exp |
e to power of number |
Math.exp(number) |
log |
Natural log of number |
Math.log(number) |
pow |
Base to exponent power |
Math.pow(base, exponent) |
max |
Greater of two numbers |
Math.max(num, num) |
min |
Lesser of two numbers |
Math.min(num, num) |
round |
Round to nearest integer |
Math.round(number) |
sqrt |
Square root of number |
Math.sqrt(number) |
These methods should come in pretty handy in creating the functions for your scripts, especially if you'd like to do some serious scientific or mathematic calculations on your Web pages. That is to say, if you know more about math than I do.
Finally, let's quickly look at another object you may have reason to use in your JavaScriptthe Date object. You can use the Date object to set the current date, perform math between different dates, and so on.
To use the Date object, you'll need to create a particular instance of that object:
todayDate = new Date();
If you create a Date object that doesn't include anything in the parentheses, it uses the current date and time, in this format:
Day Mon Date HH:MM:SS ZNE Year
Here's an example:
Thu Nov 29 13:57:46 CST 2001
You can use methods for the Date object to extract different portions of the date, such as todayDate.getDay(), or todayDay.getDate() and todayDate.getHours(). If you'd like to place the current date and time in your page, for instance, the following would do that:
<script type="text/javascript"> <!-- begin hiding var todayDate = new Date(); document.writeln ("Today is: " + " " + todayDate.getMonth() + "/" + todayDate.getDate() + "/" + todayDate.getYear() + "<br>"); document.writeln ("The time is: " + todayDate.getHours() + ":" + todayDate.getMinutes() + "<br>"); // end hiding --> </script>
The results would look something like this:
Today is: 10/5/2002 The time is: 14:31
Previous: Controlling Your JavaScript | Next: Summary |