Chapter 8. Classes
Is JavaScript an object-oriented programming language? The answer depends on who you ask (and how you phrase the question). But the general consensus is yes, with some caveats.
Outside of academic circles, object-oriented programming languages usually revolve around concepts like classes, interfaces, and inheritance. But until recently, JavaScript was an outlierâan object-oriented programming language built on functions and prototypes. Then, along came ES6, and all of sudden classes were available as a native language construct, muddying the waters. Was it just syntactic sugar or a major language evolution?
The answer lies somewhere in between. Overall, ES6 classes are a higher-level language feature built on the familiar foundation of JavaScript prototypes. But the mapping isnât exact, and the class model introduces some new subtleties that arenât completely captured in the prototype model. Furthermore, itâs likely that classes will support new object-oriented features in the future, pushing the two overlapping models farther apart.
The bottom line is this: today new development favors using classes, but prototype-based code is still common (and far from obsolete). This chapter focuses on common patterns using classes, but also explores prototypes.
Creating a Reusable Class
Problem
You want to create a reusable template for custom objects.
Solution
Use the class
keyword, and give your class a name. Inside, add a constructor function that initializes ...
Get JavaScript Cookbook, 3rd 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.