Classes and Inheritance

Learn object-oriented programming with JavaScript classes and inheritance patterns.

Present State

JavaScript supports object-oriented programming through the use of classes introduced in ES6. Classes provide a cleaner and more intuitive syntax to create objects and deal with inheritance. They act as syntactic sugar over JavaScript's prototype-based inheritance model, making it easier to build complex and reusable object-oriented structures.

Code Example

Here’s an example demonstrating class creation and inheritance:

Class and Inheritance Example

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

const dog = new Dog("Buddy");
dog.speak(); // Output: Buddy barks.
          

This code demonstrates:

  • Creating a base class Animal.
  • Extending the base class with Dog.
  • Overriding methods using inheritance.
  • Using super to refer to the parent class constructor or methods.

Description

JavaScript classes are templates for creating objects. They encapsulate data with code to work on that data.

  • Class: Defined using the class keyword. Contains a constructor and methods.
  • Constructor: A special method for initializing new instances.
  • Inheritance: Achieved using the extends keyword to create a subclass.
  • super(): Used to call the parent class's constructor or methods.

This approach simplifies the use of object-oriented programming in JavaScript by abstracting prototype chains and improving code readability and reusability.

Applications

  • Modeling real-world entities using objects and classes.
  • Building scalable front-end architecture in frameworks like React.
  • Developing reusable UI components and patterns.
  • Creating modular game engines or simulations.
  • Enhancing code organization and readability in large applications.

Multiple Choice Questions

Q1: What does the extends keyword do in JavaScript?

  • A. Creates a new object
  • B. Binds methods to a class
  • C. Allows a class to inherit from another class
  • D. Overrides the constructor

Answer: C. Allows a class to inherit from another class

Q2: How do you call the parent class’s constructor from a subclass?

  • A. this.parent()
  • B. super()
  • C. base()
  • D. constructor()

Answer: B. super()

Q3: Which of the following statements about JavaScript classes is true?

  • A. They completely replace prototypes.
  • B. They are purely syntactic sugar over prototypes.
  • C. They disable inheritance.
  • D. They must be used in ES5 code.

Answer: B. They are purely syntactic sugar over prototypes.

Q4: Which method is automatically called when an object is created from a class?

  • A. init()
  • B. setup()
  • C. constructor()
  • D. new()

Answer: C. constructor()