The JavaScript Diaries: Part 6/Page 4
[previous]
The JavaScript Diaries: Part 6
Object Methods
If methods are like verbs, then they must do something. If we look at the write
method of the document
object, we can see that it tells the JavaScript interpreter to write something into the document. Let's take a look at how other methods are created and how they are used.
First, let's create an object using the constructor function like we did before:
function computer(Type,Monitor,Drive,RAM) { this.type=Type; this.monitor=Monitor; this.drive=Drive; this.ram=RAM; }
|
Now we need to create a custom method which will act upon the object we just created.
function displaySys(sysInfo) { display = "<strong>" + sysInfo.type + "</strong><br>"; display += "Monitor: " + sysInfo.monitor + "<br>"; display += "Drive: " + sysInfo.drive + "<br>"; display += "RAM: " + sysInfo.ram + "<br>"; document.write(display+"<br>"); }
|
Finally, we need to add some data that the method can act upon. We'll do that using another function. (You have probably figured out by now that functions are very important in JavaScript. Learn how to use them and they will help organize your work. The following code could have been written without using a function but it would not have been as compact and accessible.)
function sysStats() { var sysNeed = new computer("System I Need:","17\" CRT","80 GB","512 MB"); var sysWant = new computer("System I Want:","21\" LCD","120 GB","1 GB"); displaySys(sysNeed); displaySys(sysWant); }
|
The function calls will cause the method to act upon our data to display it as we have it set up. It should look like this:
System I Need: Monitor: 17" CRT Drive: 80 GB RAM: 512 MB System I Want: Monitor: 21" LCD Drive: 120 GB RAM: 1 GB |
Wrap-Up
That's all for this time. Carefully review this material and the section on functions. Next time we'll move into the built-in objects. Until next time ... keep on scripting!
Continue on to "The JavaScript Diaries: Part 7"
[previous]
Created: July 1, 2005
URL: