HTML and CSS Reference
In-Depth Information
document . write ( fruit [ 1 ]);
//Add the following three lines
var myFruit = fruit . pop ();
document . write ( “<br>” + myFruit + “<br>” );
document . write ( fruit . length );
When you test the program from the previous section with the above changes, you'll see that
the last added element has a value of plum , and that's what is printed to the screen. However,
the length is no longer 4, but now 3. h at's because the pop() method removes the element
from the array. (By the way, the var in front of the myFruit variable is optional to declare a
variable, but it helps to distinguish it from the array elements in this listing.)
Creating your own objects
If you create a few of your own objects, you can get an idea of how objects work in the DOM.
Also, to help clarify things, from now on, a reference to an object's properties in general refers
to both properties and methods. However, when I get specii c in talking about an object's
individual parts, the reference will be either to a property (some characteristic of the object)
or a method (a function associated with the object).
Making objects is similar to declaring variables and assigning them values. h e object itself is
sort of a base of operations for doing a lot of dif erent things and having dif erent characteris-
tics. h e i rst step is simply to use a name and the keyword new . For example, the following
declares an object named AddingMachine :
AddingMachine = new Object ();
Next, to add a property, you invent a new name for the property and assign it a value. h e
object name and its property are separated by a dot ( . ). For example, the following adds a
property named firstNumber and assigns it a value of 4:
AddingMachine . firstNumber = 4 ;
Just like a variable, you can change the firstNumber value to something else.
To add a method (a function) is just as easy. However, instead of using a named function, you
use an anonymous one. For example, the following adds the value of two properties for the
AddingMachine object and sends them to the screen:
AddingMachine . total = function ()
document . write ( this . firstNumber + this . secondNumber );
h e keyword this is a reference to AddingMachine . It's the same as writing Adding
Machine.firstNumber . Notice also that function() has no name — it's anonymous.
Search WWH ::

Custom Search