Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

262 CHAPTER 6 Essential JavaScript and jQuery


Lesson 1: Creating JavaScript objects


In JavaScript, everything is an object. Strings, numbers, and functions are all objects. You have
learned how to create functions, so you already have exposure to creating objects, as you see
in this lesson.

After this lesson, you will be able to:
■■Understand basic object-oriented terminology.
■■Create JavaScript objects.

Estimated lesson time: 20 minutes

Using object-oriented terminology


In many object-oriented languages, when you want to create objects, you start by creating
a class, which is a blueprint for an object. Like a blueprint for a house, the blueprint isn’t the
house; it’s the instructions that define the type of object that you will be constructing, which
is the house. By using a house blueprint, you can create, or construct, many houses that are
based on the blueprint. Each house is an object of type house, also known as an instance of
the house type.
The developer writes the class, which is then used to construct objects. In a baseball appli-
cation, you might create a Player (classes are normally capitalized) class that has properties
for first and last name, batting average, error count, and so on. When you create your team,
you might use the Player class to create nine Player objects, each having its own properties.
Each time you construct a Player object, memory is allocated to hold the data for the player,
and each piece of data is a property, which has a name and a value.
The three pillars of object-oriented programming are encapsulation, inheritance, and
polymorphism. Encapsulation means that you hide all details except those that are required
to communicate with your object in order to simplify the object for anyone using the object.
Inheritance means that you can create an “is a” relationship between two classes, in which the
child class automatically inherits everything that is in the parent class. Polymorphism means
that you can execute a function on the parent class, but the behavior changes (morphs)
because your child class has a function that overrides the function in the parent class.
The parent class is also known as the base class, the super class, or the generalized class.
The child class is also known as the derived class, the subclass, or the specialized class. Because
it’s easy to think of actual children inheriting from parents, the terms parent and child are
usually used, but you should remember the other terms for these classes to communicate
effectively with others about object-oriented programming.
In object-oriented programming, objects can have data implemented as properties and
behaviors implemented as methods. A property is essentially a variable that is defined on

Key
Te rms

Key
Te rms

Key
Te rms

Key
Te rms
Free download pdf