JavaScript ES6 Classes: Syntax and Inheritance

JavaScript, a cornerstone of modern web development, has evolved significantly over the years. One of the most notable advancements came with the introduction of ECMAScript 6 (ES6) in 2015. Among its many features, ES6 classes provided a more structured and object - oriented way to write code in JavaScript. Before ES6, JavaScript used constructor functions and prototypes to achieve similar functionality, but classes simplified the syntax and made the code more readable and maintainable. In this blog, we will explore the syntax of ES6 classes and how inheritance works within them.

Table of Contents

  1. Fundamental Concepts of ES6 Classes
  2. Syntax of ES6 Classes
  3. Inheritance in ES6 Classes
  4. Common Practices
  5. Best Practices
  6. Conclusion
  7. References

Fundamental Concepts of ES6 Classes

In JavaScript, a class is a special type of function. It serves as a blueprint for creating objects. A class encapsulates data and the functions that manipulate that data. ES6 classes are syntactic sugar over the existing prototype - based inheritance. They provide a cleaner and more familiar syntax for developers coming from object - oriented programming languages like Java or Python.

Syntax of ES6 Classes

Class Declaration

The basic syntax for declaring a class in ES6 is as follows:

class MyClass {
    constructor() {
        // Initialization code goes here
    }

    myMethod() {
        // Method implementation
    }
}

// Creating an instance of the class
const myObject = new MyClass();

In the above example, MyClass is the name of the class. The constructor method is a special method that is called when an object is created from the class. It is used to initialize the object’s properties. The myMethod is a regular method that can be called on an instance of the class.

Class Expression

Classes can also be defined using class expressions:

const AnotherClass = class {
    constructor() {
        // Initialization code
    }

    anotherMethod() {
        // Method implementation
    }
};

const anotherObject = new AnotherClass();

Inheritance in ES6 Classes

Inheritance allows a class to inherit properties and methods from another class. In ES6, we use the extends keyword to implement inheritance.

Single Inheritance

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(); 

In this example, the Dog class extends the Animal class. The Dog class inherits the constructor and the name property from the Animal class. It also overrides the speak method to provide its own implementation.

Using super Keyword

The super keyword is used to call the constructor or methods of the parent class.

class Rectangle {
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }

    area() {
        return this.width * this.height;
    }
}

class Square extends Rectangle {
    constructor(side) {
        super(side, side);
    }
}

const square = new Square(5);
console.log(square.area()); 

Here, the Square class extends the Rectangle class. The super keyword in the Square constructor is used to call the Rectangle constructor with the appropriate arguments.

Common Practices

  • Encapsulation: Use getter and setter methods to control access to an object’s properties.
class Person {
    constructor(name) {
        this._name = name;
    }

    get name() {
        return this._name;
    }

    set name(newName) {
        if (typeof newName === 'string') {
            this._name = newName;
        }
    }
}

const person = new Person('John');
console.log(person.name); 
person.name = 'Jane';
console.log(person.name); 
  • Static Methods: Use static methods when a method doesn’t need to be called on an instance of the class.
class MathUtils {
    static add(a, b) {
        return a + b;
    }
}

console.log(MathUtils.add(2, 3)); 

Best Practices

  • Keep Classes Small and Focused: Each class should have a single responsibility. This makes the code more modular and easier to maintain.
  • Use Descriptive Names: Use meaningful names for classes, methods, and properties. This improves code readability.
  • Avoid Deep Inheritance Hierarchies: Deep inheritance hierarchies can make the code hard to understand and maintain. Try to keep inheritance levels to a minimum.

Conclusion

ES6 classes in JavaScript provide a cleaner and more structured way to implement object - oriented programming concepts. The syntax is more familiar to developers coming from other object - oriented languages, making it easier to write and understand code. Inheritance using the extends and super keywords allows for code reuse and the creation of hierarchical relationships between classes. By following common and best practices, developers can write more maintainable and robust JavaScript code.

References