HTML and CSS Reference
In-Depth Information
Figure 8.4
An object and its properties.
8.2
Classes and User-Defined Functions
JavaScript ain't got no class! If you are familiar with Java or C++ you may be wondering
how to create a class in JavaScript. A class is a template or blueprint that describes the
properties and behavior of all objects that belong to that specific class, so you may have
a Car class or a House class or a Widget class. A Car class would be defined with the
properties and methods for a Car and then you could create as many Car objects as you
want using the class as a template. But JavaScript doesn't have classes in the traditional
sense. It doesn't have a
class
keyword. We must develop the notion of classes in a differ-
ent way. A new JavaScript class is defined by creating a simple function. The name of the
function will serve as the class name for an object, and the function will define its prop-
erties and methods; it serves as a blueprint or prototype of the object. When the function
is called with the
new
keyword, it acts as a constructor; that is, it builds the new object
and then returns a reference to it. We can say that if you call the
Book()
constructor func-
tion, it returns a reference to a new
Book
object, an instance of the Topic class.
Internally, JavaScript creates an object, and then calls the constructor function. Inside
the constructor, the variable
this
is initialized to point to this newly created object. The
this
keyword is a sort of shorthand reference that keeps track of the current object. When
a function is used as a constructor, the
this
keyword is used to set the properties for the
object that was just created. In this way you can create as many objects as you need and
JavaScript
this
will refer to the current object. In Example 8.4, a function is used to create
a Book class with two properties, a title and an author. The
this
keyword refers to the
current Book object.
Methods can be assigned to an object in the constructor function so that the method
can be applied to multiple instances of an object. In Example 8.5, two methods are cre-
ated in the Topic constructor function called
uppage()
and
backpage().
Any Book object
has access to these methods.