To accept an object literal for options, the function simply
accepts one parameter:
function func( options )
{
alert(options.a); // alert's 5
}
var myOptions = { a: 5, b: 6, c: 7 };
func( myOptions );
CHAPTER 3 n OBJECT-ORIENTED PROGRAMMING 67
To have default options, you can declare them within the function and then overwrite
them with anything you pass into the function:
function func( updates )
{
var options = { a: 5, b: 6, c: 7 };
for (var property in updates) {
options[property] = updates[property];
}
alert(options.a); // alert's 8
}
func( {a:8} );
The for loop copies all the properties in the updates object and attaches them to the
internal options object.
Namespaces
Tangentially related to using object literals is the use of a namespace while developing. A
namespace is a container for a bunch of related items. Namespaces are common and even
a requirement in other languages such as Java. Although JavaScript doesn??™t actually have a
specific construct to do namespacing, you can use the object literal and a naming convention
to accomplish the same thing.
Using a namespace has a couple of benefits:
??? It keeps the global object (also known as the window object) cleaner. With scripts getting
larger and more complicated, along with the use of third-party scripts, there
would be a much higher chance of naming collisions if everything was at the global
level. Both the Prototype JavaScript library and the jQuery library use $() to retrieve
HTML elements, but they behave in different ways, and the object returned will have
different methods available to you.
Pages:
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124