Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

278 CHAPTER 6 Essential JavaScript and jQuery


An IIFE (pronounced iffy) is an anonymous function expression that has a set of parenthe-
ses at the end of it, which indicates that you want to execute the function. The anonymous
function expression is wrapped in parentheses to tell the JavaScript interpreter that the func-
tion isn’t only being defined; it’s also being executed when the file is loaded.
In this IIFE, the first line creates the myApp namespace if it doesn’t already exist, which
represents the singleton object that is used as the namespace. Next, an ns variable (for
namespace) is created as an alias to the namespace to save typing within the IIFE, so ns can
be used in place of this.myApp. After that, the private members of the namespace are defined
by using the var keyword. Car and Truck are public, so they are prefixed with ns.
If you’re wondering how you would create a sub-namespace under myApp, the following
example shows how you can add a billing namespace under the myApp namespace.
(function () {
this.myApp = this.myApp || {};
var rootNs = this.myApp;
rootNs.billing = rootNs.billing || {};
var ns = rootNs.billing;

var taxRate = .05;
ns.Invoice = function () { };
}());

This example also implements an IIFE to create the namespace. First, the myApp
namespace is created if it doesn’t already exist and is assigned to a local rootNs variable to
save typing inside the namespace. Next, the billing namespace is created and assigned to the
local ns variable to save typing inside the namespace. Finally, the private taxRate property is
defined while the public Invoice is defined.

Implementing inheritance


JavaScript provides the ability to implement inheritance, which is useful when you can define
the relationship between two objects as an “is a” relationship. For example, an apple is a
fruit, an employee is a person, and a piano is an instrument. You look for “is a” relationships
because they provide an opportunity to implement code reuse. If you have several types of
vehicles, you can create Vehicle with the common vehicle traits defined in it. After Vehicle is
created, you can create each vehicle type and inherit from Vehicle so you don’t need dupli-
cate code in each vehicle type.
As an example of inheritance, start by defining the base class. Using the Vehicle example,
the following is an example of a Vehicle base class.
var Vehicle = (function () {
function Vehicle(year, make, model) {
this.year = year;
this.make = make;
this.model = model;
}

Key
Te rms
Free download pdf