Chapter 9. Classes, Constructors, and Prototypes
JavaScript objects were introduced in Chapter 7. That chapter treated each object as a unique set of properties, different from every other object. In many object-oriented programming languages, it is possible to define a class of objects and then create individual objects that are instances of that class. You might define a class named Complex to represent and perform arithmetic on complex numbers, for example. A Complex object would represent a single complex number and would be an instance of that class.
JavaScript does not support true classes the way that languages like Java, C++, and C# do.[*] Still, however, it is possible to define pseudoclasses in JavaScript. The tools for doing this are constructor functions and prototype objects. This chapter explains constructors and prototypes and includes examples of several JavaScript pseudo-classes and even pseudosubclasses.
For lack of a better term, I use the word “class” informally in this chapter. Be careful, however, that you don’t confuse these informal classes with the true classes of JavaScript 2 and other languages.
Constructors
Chapter 7 showed you how to
create a new, empty object either with the object literal {}
or with the following expression:
new Object( )
You have also seen other kinds of JavaScript objects created with a similar syntax:
var array = new Array(10); var today = new Date( );
The new
operator must be followed by a function invocation. It creates a new object, ...
Get JavaScript: The Definitive Guide, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.