In ES6, which statement correctly creates a class that extends another class?

Understanding Class Inheritance in ES6

In the ECMAScript 6 (ES6) version of JavaScript, classes were introduced as a way to enhance the object-oriented programming capabilities of the language. Among these enhancements was the ability to easily create subclasses using the extends keyword. This feature facilitates code reuse by allowing you to create a new class, known as a subclass, which inherits the properties and methods of an existing class, referred to as a superclass or base class.

The ES6 extends keyword in subclass creation

The correct way to create a subclass that extends a base class in ES6 is as follows:

class SubClass extends BaseClass {}

In this statement, SubClass is a new class that extends the BaseClass. This means it inherits all the methods and properties of BaseClass. Here's a simple example for clarity:

class BaseClass {
    constructor() {
        this.message = "Hello from BaseClass!";
    }

    greet() {
        console.log(this.message);
    }
}

class SubClass extends BaseClass {
    constructor() {
        super(); // Call the parent class constructor
        this.message = "Hello from SubClass!";
    }
}

let instance = new SubClass();
instance.greet(); // Output: Hello from SubClass!

In the above example, SubClass extends BaseClass and redefines the message property in its constructor. When greet is called on an instance of SubClass, it displays the message "Hello from SubClass!" This shows that SubClass has inherited the greet method from BaseClass.

Understanding the different possibilities

The other options listed in the quiz question do not create a subclass in ES6. Here is a brief analysis of each:

  1. class SubClass inherits BaseClass {}: JavaScript does not use the inherits keyword for subclassation.
  2. SubClass.prototype = new BaseClass();: While this may work in older versions of JavaScript to set up prototype-based inheritance, it is not the way to declare a class extending another class in ES6. ES6 uses the more declarative and understandable class...extends syntax.
  3. class SubClass: BaseClass {}: Here, the colon is syntaxically incorrect. JavaScript uses the class...extends syntax for class inheritance.

Best practices and insights

While ES6 classes ease JavaScript's ability to create subclasses, you should use inheritance sparingly in your code. Overuse of inheritance can lead to large classes with lots of functionality, which may become hard to maintain over time. Instead, try to adhere to the principle of single responsibility: each class should have only a single responsibility. This could make your code more modular, easier to test, and more maintainable. Also, always use the super() function in subclasses' constructors to ensure that the parent class's constructor is called and properly set up.

Do you find this helpful?