Lesson 1: Creating JavaScript objects CHAPTER 6 277
var myApp = {};
myApp.vehicleCount = 5;
myApp.vehicles = new Array();
myApp.Car = function () { }
myApp.Truck = function () { }
myApp.repair = {
description: 'changed spark plugs',
cost: 100
};
In this sample, myApp is the only entry in the global namespace. It represents the name of
the application and its root namespace. Notice that object literal syntax is used to create an
empty object and assign it to myApp. Everything else is added to the object. Sub-namespaces
can also be created and assigned to myApp.
You can see that a namespace was created by creating an object. Although only one entry
is made in the global namespace, all the members of myApp are globally accessible. In addi-
tion, if you create a namespace for your application, and your application has many JavaScript
files, you might want to have logic to create the namespace object only if it hasn’t been
created. In the following example, the code for myApp is modified to create the namespace
object if it doesn’t already exist. This code uses the OR operator to create a new object if
myApp does not have a value.
var myApp = myApp || {};
You can use the object techniques already defined in this lesson to make some members
of the namespace private and some public. The difference is that the namespace is a single-
ton object, so you create a single instance for the namespace. You don’t need to worry about
functions defined in the constructor function consuming additional memory for each instance
because there is only one instance. Here is an example of the use of an immediately invoked
function expression (IIFE) to create the myApp namespace in which Car and Truck are public,
but vehicleCount, vehicles, and repair are private.
(function () {
this.myApp = this.myApp || {};
var ns = this.myApp;
var vehicleCount = 5;
var vehicles = new Array();
ns.Car = function () { }
ns.Truck = function () { }
var repair = {
description: 'changed spark plugs',
cost: 100
};
}());