Lesson 28. Extending classes

 

After reading lesson 28, you will

  • Know how to extend classes to create more customized classes
  • Learn how to use libraries that provide a base class
  • Understand how inheritance works with classes
  • Know how to use super to invoke functions on the superclass

The best feature classes offer over traditional constructor function declarations is their ease of extension. Many consider the syntax for extending constructor functions clunky. This has led many library authors to create their own ways to extend base objects in their libraries. With built-in extendable classes, developers can learn one simple syntax that can be used everywhere. One crucial aspect to keep in mind when extending classes in JavaScript, however, is that they still use prototypal inheritance.

Consider this

In the following code, you have a plane object and a jet object. In a sense, the jet object extends the plane object because it copies all of its properties and overrides its fly method. If the jet’s fly method has overlapping logic with the plane’s fly method, how would you go about making them able to share code across the two methods?

 const plane = {
   type: 'aircraft',
   fly() {
     // make the plane fly
   }
 }
 const jet = Object.assign({}, plane, {
   fly() {
     // make the jet fly faster
   }

});

28.1. Extends

28.2. Super

28.3. A common gotcha when extending classes

Summary