30 Days of JAVASCRIPT #12/30

3. Classes in JavaScript

Classes in JavaScript are a way to create objects and define their properties and methods. They were introduced in ECMAScript 2015 (ES6) to provide a cleaner way to follow object-oriented programming patterns. In this blog post, we will discuss everything about classes in JavaScript with an example code.

Defining Classes

Classes in JavaScript are built on prototypes but have some syntax and semantics that are unique to classes. A class can be defined in two ways: a class expression or a class declaration.

// Class declaration
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  sayHello() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

// Class expression
const Animal = class {
  constructor(name) {
    this.name = name;
  }

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

In the above code, we define a Person class using the class declaration syntax and an Animal class using the class expression syntax. We then create objects of these classes and call their methods.

Inheritance

Classes in JavaScript support inheritance, which means that a class can inherit properties and methods from another class. This is done using the extends keyword.

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

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

class Dog extends Animal {
  constructor(name) {
    super(name);
  }

  speak() {
    console.log(`${this.name} barks.`);
  }
}

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

In the above code, we define an Animal class and a Dog class that extends the Animal class. We then create an object of the Dog class and call its speak() method.

Static Methods

Classes in JavaScript also support static methods, which are methods that belong to the class itself and not to its instances. They are defined using the static keyword.

class MathUtils {
  static add(a, b) {
    return a + b;
  }

  static subtract(a, b) {
    return a - b;
  }
}

console.log(MathUtils.add(2, 3)); // Output: 5
console.log(MathUtils.subtract(5, 3)); // Output: 2

In the above code, we define a MathUtils class with two static methods add() and subtract(). We then call these methods without creating an object of the class.In conclusion, classes in JavaScript provide a cleaner and more elegant syntax for creating objects and defining their properties and methods. They support inheritance and static methods, which make them more powerful and flexible.