Thinking of Objects as Associative Arrays
Hashtable, dictionaries, and others. Unlike with normal arrays, where the key is numeric (as in
bookNames), 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:
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:
The key of an element doesn't have to be literal; it can even be specified through a variable:
Table class that we discussed earlier can be represented like this:
Creating Object Members on the Fly
var keyword or are received as function parameters. They aren't accessed using
this, and they aren't accessible through function instances, thus acting like private members. Variables can, however, be accessed by closure functions.
If you want to test this, modify the Table function as shown below.
This time we persist the values received as parameters as local variables named
_columns. Note they aren't referred to using
this any more. Local variables names don't need to start with an underscore, but this is a useful naming convention that specifies they are meant to be used as private members. You can make a short test that the "private" members can't be accessed from outside the function, and that
getCellCount() still works, using code such as the following. The results are shown in Figure 3-5.
This exercise reveals that
_columns aren't accessible from outside the function's scope. Their values read undefined because there are no fields named
_columns in the
Table function. The
getCellCount() function, on the other hand, can read
_columns as variables because they are in the same closure. As you can see, although the implementation and behavior are somewhat different than in C#, you still have a way of defining internal (private) members inside a function.
[This is an excerpt from the book, Microsoft AJAX Library Essentials: Client-side ASP.NET AJAX 1.0 Explained, by Cristian Darie, Bogdan Brinzarea . Published by Packt Publishing Ltd., 2007