9 Objects, prototypes, and classes

 

This chapter covers

  • Object properties, getters, and setters
  • Proxying objects
  • Extending objects with prototypes
  • Building classes with inheritance

When we think of JavaScript objects, we tend to think of a set of key-value pairs, like JSON objects. But objects in JavaScript can be much richer than that. Their members can have special properties, like being read-only or excluded from iteration. They can be proxied to intercept certain calls. And most curiously of all, they offer a built-in inheritance mechanism known as a prototype, which can be modified at runtime to dynamically update the behavior of countless objects at once.

In the early days of JavaScript, prototypes were an essential feature of the language. Today, though, they’ve largely been supplanted by classes, which were introduced by ES2015. Classes provide a relatively simple and intuitive way to create different types of object, complete with inheritance. They’re also a better fit with TypeScript than the old prototypal inheritance model.

As a JavaScript Ninja, you may find yourself faced with challenges that involve all of these language features—even prototypes, which remain important to the behavior of objects even as their direct usage has fallen out of favor. To truly understand classes, you need to understand prototypes.

With that in mind, let’s begin our journey into the world of JavaScript objects!

9.1 Customizing objects with properties

9.1.1 Defining getters and setters

9.1.2 Defining and redefining object properties

9.2 Intercepting object access with Proxy and Reflect

9.3 Dynamic inheritance with prototypes

9.3.1 Fallbacks as inheritance

9.3.2 Building prototyped objects with constructors

9.4 Classic OOP with class and extends

9.4.1 Classes as shorthand for prototypes

9.4.2 Inheriting across classes

9.4.3 Restricting access with private elements

9.5 Summary