Dot notation is what I used in
the previous examples. If you??™ve done any programming in languages such as Java or C++, dot
notation is very familiar. You can even chain commands together (something I do often with
string manipulation).
Let??™s say you need to take a string that a user typed in and want to clean it up to use in the
search engine:
// The next statement would result in "what up dog"
"What up, dog!".toLowerCase().replace(/[^a-z0-9 ]/g,"");
Bracket notation is similar, except properties are referenced through square brackets like
an array. Using the example from the last section, you would do this:
alert(foo["value"]); // you should see "5"
You can even call methods by adding the brackets (along with any possible parameters on
to the end):
foo["mymethod"]();
You can still chain items using bracket notation, too:
// The next statement would still result in "what up dog"
"What up, dog!"["toLowerCase"]()["replace"](/[^a-z0-9 ]/g,"");
This is a little harder to read, so most people stick to the dot notation. Bracket notation
does give you the benefit of being able to use a variable to execute a function on an object:
function manipulateString(str, func)
{
return str[func]();
}
newstring = manipulateString("WHAT UP", "toLowerCase"); // newstring = "what up"
In the next two chapters, you??™ll see some practical implementations.
CHAPTER 2 n HTML, CSS, AND JAVASCRIPT 23
Prototypes
JavaScript is prototype-based, so you essentially clone existing objects to create new objects.
Pages:
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68