Classes and Inheritance in JavaScript
Key Concepts
- Classes
- Constructor
- Inheritance
- Super
- Static Methods
- Instance Methods
Classes
Classes in JavaScript are templates for creating objects. They encapsulate data with code to work on that data. Classes are in fact "special functions", and just as you can define function expressions and function declarations, the class syntax has two components: class expressions and class declarations.
Example:
class Animal { constructor(name) { this.name = name; } speak() { console.log(${this.name} makes a noise.); } } let animal = new Animal('Animal'); animal.speak(); // Outputs: Animal makes a noise.
Constructor
The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A constructor can use the super keyword to call the constructor of the super class.
Example:
class Dog extends Animal { constructor(name, breed) { super(name); this.breed = breed; } } let dog = new Dog('Rex', 'German Shepherd'); console.log(dog.name); // Outputs: Rex console.log(dog.breed); // Outputs: German Shepherd
Inheritance
Inheritance is a mechanism that allows a class to inherit properties and methods from another class. The class that inherits is called a subclass or derived class, and the class from which it inherits is called the superclass or base class.
Example:
class Cat extends Animal { speak() { console.log(${this.name} meows.); } } let cat = new Cat('Whiskers'); cat.speak(); // Outputs: Whiskers meows.
Super
The super keyword is used to call corresponding methods of the super class. This is one advantage over the prototype-based inheritance.
Example:
class Lion extends Cat { speak() { super.speak(); console.log(${this.name} roars.); } } let lion = new Lion('Simba'); lion.speak(); // Outputs: Simba meows. Simba roars.
Static Methods
Static methods are called without instantiating their class and cannot be called through a class instance. Static methods are often used to create utility functions for an application.
Example:
class Calculator { static add(a, b) { return a + b; } } console.log(Calculator.add(5, 3)); // Outputs: 8
Instance Methods
Instance methods are methods that are available on instances of a class, created via the new keyword. These methods can access and modify the instance data.
Example:
class Circle { constructor(radius) { this.radius = radius; } getArea() { return Math.PI * Math.pow(this.radius, 2); } } let circle = new Circle(5); console.log(circle.getArea()); // Outputs: 78.53981633974483