JavaScript API Reference/Creating Custom Java Script Objects

Objects with Nested Arrays or Other Objects

You have seen that objects can contain properties and functions. In JavaScript, functions are objects and can be assigned to variables – this is why the Base object syntax is very similar for properties and functions.

In fact, properties can contain arbitrary complex JavaScript objects. Two practical examples include nested objects and nested arrays:

var MapMarker = Base.extend({
// summary text line, displayed as a tooltip
summary: '',

// HTML content, displayed when user clicks on the marker
content: '',

// X and Y coordinates of the marker on the map
coordinates: '' ,

// object that contains a drill-down restriction
restriction: null,


// array that contains commands executed when the user
// clicks to drill-down into the marker
commands: null,


// constructor function
constructor: function(summary, content, coordinates) {
this.summary = summary;
this.content = content;
this.coordinates = coordinates;

// initialize the empty object
this.restriction = {};


// initialize the empty array
this.commands = [];

}
});


As you can see, nested objects and arrays must be initialized in the object constructor. You can also pass values for nested array or objects as constructor parameters from the application code:

// constructor function
constructor: function(summary, content, coordinates, restriction, commands) {
this.summary = summary;
this.content = content;
this.coordinates = coordinates;

// initialize the empty object
this.restriction = {};
if (valueExists(restriction)) {
this.restriction = restriction;
}


// initialize the empty array
this.commands = [];
if (valueExists(commands)) {
this.commands = commands;
}

}