Thinking of Objects as Associative Arrays
A key element in understanding JavaScript objects is understanding the notion of associative arrays, which are nothing more than collections of (key, value) pairs. As a .NET developer you have worked with associative arrays represented by classes such as NameValueCollection, Hashtable, dictionaries, and others. Unlike with normal arrays, where the key is numeric (as in bookNames[5]), the key of an associative array is usually a string, or even other kinds of objects that can represent themselves as strings. For example, take a look at the following code snippet, where we retrieve the name of the book by specifying a unique string value that identifies that book:
// retrieve the name of the book
bookName = bookNames["ASP_AJAX"];
The concept is simple indeed. In this case, the key and the value of the bookNames associative array are both strings. This associative array could then be represented by a table like this:
Key Value
ASP_AJAX Microsoft AJAX Library Essentials
AJAX_PHP AJAX and PHP: Building Responsive Web Applications
SEO_ASP Professional Search Engine Optimization with ASP.NET
The table above can be represented in JavaScript, as an associative array, like this:
// define a simple associative array
var bookNames =
{ "ASP_AJAX" : "Microsoft AJAX Library Essentials",
"AJAX_PHP" : "AJAX and PHP: Building Responsive Web Applications",
"SEO_ASP" : "Professional Search Engine Optimization with ASP.NET"
};
The key of an element doesn't have to be literal; it can even be specified through a variable:
// store the book ID in a variable
var bookId = "ASP_AJAX";
// display the name of the book
document.write("The name of " + bookId +
" is " + bookNames[bookId] + "
");
In JavaScript, however, the implementation of the associative array is more powerful, in that it makes no restriction on the type of the value of the (key, value) pair. The value can be a number, a string, a date, or even a function! This flexibility allows us to represent JavaScript objects as associative arrays. For example, an instance of the Table class that we discussed earlier can be represented like this:
// create Table object
var t =
{ rows : 3,
columns : 5,
getCellCount : function () { return this.rows * this.columns; }
};
// display object field values
document.writeln("Your table has " + t.rows + " rows" +
" and " + t.columns + " columns
");
// call object function
document.writeln("The table has " + t.getCellCount() +
" cells
");
This example, and the one presented earlier with book names, can be tested online at http://www.cristiandarie.ro/asp-ajax/Associative.html, and the result is presented in Figure 3-4.

NOTE: The literal notation of creating JavaScript objects has one weakness—it can only be used to describe objects. In other words, using the literal notation you can only define (key, value) pairs, but you can't create classes, class constructors, or other reusable components of code.
Trackback(0)
|