One Problem, Many Solutions
In case you're locked into the inheritance paradigm, this section demonstrates multiple approaches to achieving similar results for a simple problem: modeling a circle object. In addition to being a good exercise in demonstrating some out-of-the-box thinking, this section also applies some of the language tools you learned about in Chapter 2.
Typical JavaScript Inheritance
JavaScript programmers have been simulating classes with
Function objects for quite a while—sometimes at the expense of
abusing the language, other times effectively to solve a particular
problem. The inherent nature of a JavaScript Function object is the
very mechanism that provides the footing for simulating classes.
Namely, it acts as a constructor function that
is used in conjunction with the new operator to create object instances,
and it provides the template for those object instances that are
created.
To illustrate, Example 10-1
provides a short code snippet that approximates a simple Shape class in JavaScript. Note that by
convention, classes usually begin with a capital letter.
Tip
For just an added touch of simplicity, the examples in this chapter do not use namespaces for qualifying objects. In general, however, you will want to use namespaces, and we'll pick back up using namespaces in Chapter 12.
Example 10-1. A typical JavaScript class
// Define a class function Shape(centerX, centerY, color) { this.centerX = centerX; this.centerY = centerY; this.color = color; }; // Create ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access