11.12.2012 Views

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

myArray[1] = 5;<br />

myArray[2] = "Thomas";<br />

myArray[3] = true;<br />

As briefly mentioned, arrays are actually objects and have a variety of properties and methods<br />

that can be used to manipulate them. <strong>The</strong>se features will be discussed at length in Chapter 7.<br />

However, let‘s first take at least a brief look at objects in <strong>JavaScript</strong>.<br />

Objects<br />

Objects can hold any type of data and are the primary mechanism by which useful tasks are<br />

carried out. <strong>The</strong> browser provides a large number of objects for you to use. For example, you<br />

can interact with the user through the Window object or modify the contents of a Web page<br />

with the Document object.<br />

Data contained in an object are said to be properties of the object. Properties are accessed with<br />

the ―dot‖ operator, which is simply a period followed by the property name. <strong>The</strong> syntax is<br />

objectname.propertyname<br />

For example, you would access the lastModified property of the Document object as<br />

document.lastModified.<br />

Functions contained in an object are said to be methods of the object. Methods are also<br />

accessed with the dot operator:<br />

objectname.methodname()<br />

In fact, we have already used methods in our previous examples. <strong>The</strong> write() method of the<br />

Document object was used to output text to the screen:<br />

document.write("Hello <strong>JavaScript</strong> world!");<br />

You‘ll notice that when using objects, the length of the identifier required to access a particular<br />

property can get quite long. For example, writing document.write might become tiresome, as<br />

would accessing even more deeply nested sub-objects. By using the keyword with, we can<br />

avoid referencing the full path to an object‘s property or method:<br />

with (document)<br />

{<br />

}<br />

write("this is easier ");<br />

write("than writing out ");<br />

write("the whole path");<br />

Besides using built-in objects such as Document or Window, you can create your own objects<br />

using the keyword new. <strong>The</strong> use of new was briefly demonstrated with the array examples in<br />

the previous section. You can also destroy a property or element in an array using the keyword<br />

delete. For example, here we define an array element and then quickly destroy it.<br />

var myArray = new Array(4);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!