Class-Based Inheritance in JavaScript

Class-based inheritance in JavaScript offers a syntactical advantage by utilizing the class and extends keywords to define inheritance hierarchies. This approach simplifies the representation of inheritance, making it more familiar to developers from class-oriented languages like Java or C#. Essentially, class-based inheritance is syntactic sugar over constructor functions, abstracting away the complexity of prototype references and providing a cleaner, more structured way to manage object-oriented programming in JavaScript.

Key Concepts

Class and Extends

In JavaScript, inheritance is configured using the class and extends keywords. Although this syntax appears significantly different from direct prototype references, it achieves the same outcome as the pseudoclassical model using constructor functions. The class keyword is used to define a class, while extends is used to create a subclass that inherits from a parent class.

Example: Transaction and HashTransaction

To illustrate class-based inheritance, consider the following example of Transaction and HashTransaction classes:

class Transaction {
   sender = '';                                          
   recipient = '';                                        
   funds = 0.0;
   #feePercent = 0.6;                                     
   
   constructor(sender, recipient, funds = 0.0) {
      this.sender = sender;
      this.recipient = recipient;
      this.funds = Number(funds);
   }
   
   displayTransaction() {
      return `Transaction from ${this.sender} to ${this.recipient}           
        for ${this.funds}`;
   }
 
   get netTotal() {
     return  Transaction.#precisionRound(this.funds * this.#feePercent, 2);
   }
 
   static #precisionRound(number, precision) {            
      const factor = Math.pow(10, precision); 
      return Math.round(number * factor) / factor;
   }
}
 
class HashTransaction extends Transaction {               
   transactionId;
   constructor(sender, recipient, funds = 0.0) {
      super(sender, recipient, funds);                    
      this.transactionId = this.calculateHash();
   }        
   calculateHash() {
     const data = [
         this.sender,
         this.recipient,
         this.funds
       ].join('');
     let hash = 0, i = 0;
     while (i < data.length) {
         hash = ((hash << 5) - hash + data.charCodeAt(i++)) << 0;
     }
     return hash**2;
   }
 
   displayTransaction() {      
      return `${this.transactionId}: ${super.displayTransaction()}`;
   }
 }
 
const tx = new HashTransaction('luis@tjoj.com', 'luke@tjoj.com', 10);
tx.displayTransaction(); 
 
// Prints:
// 64284210552842720: Transaction from luis@tjoj.com to luke@tjoj.com for 10

In this example, HashTransaction extends Transaction, inheriting its properties and methods. The super keyword is used to call the parent class's constructor, ensuring that the prototype chain is set up correctly.

[Figure 2.4: Class Inheritance Structure](https://livebook.manning.com/book/the-joy-of-javascript/chapter-2/142)

Figure 2.4 Building the HashTransaction class and its ancestor Transaction. Instances of HashTransaction will inherit all the public fields present in the parent. Using class and extends properly sets up the prototype chain so that property lookup is done effectively and constructor references line up perfectly. Figure 2.4 Building the HashTransaction class and its ancestor Transaction. Instances of HashTransaction will inherit all the public fields present in the parent. Using class and extends properly sets up the prototype chain so that property lookup is done effectively and constructor references line up perfectly.

Figure 2.4 illustrates the inheritance structure of the HashTransaction class and its ancestor Transaction. Instances of HashTransaction inherit all public fields from the parent class. The use of class and extends ensures that the prototype chain is correctly established, allowing for effective property lookup and accurate constructor references.

Advantages of Class-Based Inheritance

Classes in JavaScript provide a well-defined structure, abstracting away the mundane details of prototype management. This makes them less error-prone and offers a syntactical advantage for grouping data and behavior cohesively. The class and extends keywords simplify the mental model of inheritance, making third-party libraries for inheritance, such as Prototype’s extend, Lodash’s _.extend, or Node’s util.inherits, largely obsolete.

FAQ (Frequently asked questions)