Chapter 7. Object orientation with prototypes
This chapter covers
- Exploring prototypes
- Using functions as constructors
- Extending objects with prototypes
- Avoiding common gotchas
- Building classes with inheritance
You’ve learned that functions are first-class objects in JavaScript, that closures make them incredibly versatile and useful, and that you can combine generator functions with promises to tackle the problem of asynchronous code. Now we’re ready to tackle another important aspect of JavaScript: object prototypes.
A prototype is an object to which the search for a particular property can be delegated to. Prototypes are a convenient means of defining properties and functionality that will be automatically accessible to other objects. Prototypes serve a similar purpose to that of classes in classical object-oriented languages. Indeed, the main use of prototypes in JavaScript is in producing code written in an object-oriented way, similar to, but not exactly like, code in more conventional, class-based languages such as Java or C#.
In this chapter, we’ll delve into how prototypes work, study their connection with constructor functions, and see how to mimic some of the object-oriented features often used in other, more conventional object-oriented languages. We’ll also explore a new addition to JavaScript, the class keyword, which doesn’t exactly bring full-featured classes to JavaScript but does enable us to easily mimic classes and inheritance. Let’s start exploring.