This section provides a quick description of access object properties using the associate array formats object_name['property_name']. A tutorial example is provided on how to use objects as associate arrays.
In previous section, I mentioned that methods of an object are managed in the same as properties in JavaScript.
This leads to another nice feature of JavaScript objects:
Objects in JavaScript are really associated arrays, which contains a collection of key-value pairs.
Keys represent property names and method names, and values represent property values and function definitions.
Now you know how to refer to a method property or a method in two ways:
Here is a tutorial example on how to access object's properties and methods in the format of an associate arrays:
<html>
<!-- Object_Associate_Array.html
Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head>
<title>Objects and Associate Arrays</title>
</head>
<body>
<pre>
<script type="text/javascript">
// Using "this" to get the properties
function myToString() {
return '"'+this.title + '" by '+this.author;
}
// Using object literal format
var myBook = {
author: "Herong Yang",
title: "JavaScript Tutorials",
toString: myToString
};
// Adding a new property
myBook['date'] = 2008;
// Getting properties values via different format
document.writeln("myBook.title: "+myBook.title);
document.writeln("myBook['title']: "+myBook['title']);
document.writeln("myBook.date: "+myBook.date);
document.writeln("myBook['date']: "+myBook['date']);
document.writeln("myBook.toString: "+myBook.toString);
document.writeln("myBook['toString']: "+myBook['toString']);
// Checking property data types
document.writeln();
document.writeln("myBook.title Type: "+(typeof myBook.title));
document.writeln("myBook['date'] Type: "+(typeof myBook['date']));
document.writeln("myBook.toString Type: "
+(typeof myBook.toString));
</script>
</pre>
</body>
</html>
If you run this tutorial example, you will see the following output, which confirms my understanding
that the dot (.) operator and associate array element operator ([]) are interchangeable.
myBook.title: JavaScript Tutorials
myBook['title']: JavaScript Tutorials
myBook.date: 2008
myBook['date']: 2008
myBook.toString: function myToString() {
return "\"" + this.title + "\" by " + this.author;
}
myBook['toString']: function myToString() {
return "\"" + this.title + "\" by " + this.author;
}
myBook.title Type: string
myBook['date'] Type: number
myBook.toString Type: function
The output also shows that as an object property, the value of a method is the function definition.