The JavaScript Diaries: Part 6/Page 3
[previous] [next]
The JavaScript Diaries: Part 6
function computer(monitor,hd,ram) { this.monitor=monitor; this.hd=hd; this.ram=ram; }
Let's look at what we did here:
|
Now we need to create a new instance of the object. We'll create two of them. (You can create as many instances of the object as you need, limited by memory of course.)
var sysNeed = new computer("17\"","80GB","512MB"); var sysWant = new computer("21\"","120GB","1GB");
Let's break this down and see what we've done:
|
Now, we need to write some code to display those properties:
document.write("I want a "+sysWant.monitor+" screen<br>"); document.write("but I'll settle for a "+sysNeed.monitor+".<br><br>"); document.write("The "+sysWant.hd+" hard drive<br>"); document.write(" should work with "+sysNeed.ram+" of RAM.<br><br>"); document.write("I really would like to have "+sysWant.ram+" of RAM.");
(I have shortened the lines above for display purposes but you could code them into three lines, or less, if you wish.)
Let's take a look at how this is written (we'll only break down the first two lines as the others are basically the same):
|
The printout from the script should look like this:
I want a 21" screen but I'll settle for a 17". The 120GB hard drive should work with 512MB of RAM. I really would like to have 1GB of RAM. |
An Object Initializer (a.k.a. "Object Literal")
Another method that could be used when you have a limited amount of information is an object initializer (a.k.a. object literal). There is no need to create a new instance of the object. The format is:
objectName={property:value}
In our preceding script, in place of the constructor function, you would write it as follows:
sysNeed = {monitor:"17\"",hd:"80GB",ram:"512MB"} sysWant = {monitor:"21\"",hd:"120GB",ram:"1GB"}
You wouldn't need to set up the variables. Just replace the script in the
head with the one above and then reuse the same document.write
statements.
Let's take another look at the document.write()
statement that
we've been using. Does it look familiar now, in light of our study of objects?
JavaScript has several built-in objects and document
is one of
them. It's also a property of the window
object. Technically, we
should write it as: window.document.write()
but since there can only
be one document in a window at a time, references to objects inside the document
can eliminate the window
portion of the code, as it is assumed.
So we see that the document
is a property of the window
object. It's also an object itself. The write
command is a method
of the document
property. (Remember, methods are like verbs.) We'll
study the built-in objects in a later installment.
Now, let's take a look at methods.
[previous] [next]
Created: July 1, 2005
URL: