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.

<strong>The</strong> result is<br />

As you can see, the simpleExample property has undefined value just as any nonexistent<br />

property would.<br />

Note C++ and Java programmers should be aware that <strong>JavaScript</strong>’s delete is not the same as<br />

in those languages. It is used only to remove properties from objects and elements from<br />

arrays. In the previous example, you cannot delete myString itself, though attempting to<br />

do so will fail silently.<br />

Accessing Properties with Array Syntax<br />

An equivalent but sometimes more convenient alternative to the dot operator is the array ([ ])<br />

operator. It enables you to access the property given by the string passed within the brackets.<br />

For example:<br />

var myString = new String("Hello world");<br />

alert(myString["length"]);<br />

myString["simpleExample"] = true;<br />

alert(myString.simpleExample);<br />

delete myString["simpleExample"];<br />

Some programmers prefer this method of accessing properties simply for stylistic reasons.<br />

However, we‘ll see in later sections another reason to favor it: it can be more powerful than the<br />

dot-operator syntax because it lets you set and read properties with arbitrary names, for<br />

example, those containing spaces.<br />

Methods<br />

Properties that are functions are called methods. Like properties, they are typically accessed<br />

with the dot operator. <strong>The</strong> following example illustrates invoking the toUpperCase() method of<br />

the String object:<br />

var myString = new String("am i speaking loudly? ");<br />

alert(myString.toUpperCase());<br />

You could also use the array syntax,<br />

var myString = new String("am i speaking loudly? ");<br />

alert(myString["toUpperCase"]());<br />

but this convention is rarely used.<br />

Setting instance methods is just like setting instance properties:<br />

var myString = new String("Am I speaking loudly? ");

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

Saved successfully!

Ooh no, something went wrong!