JavaScript Classes


What are classes in JavaScript?

Classes in JavaScript are a syntactical sugar over the existing prototype-based inheritance. They provide a clearer and more concise way to create objects and handle inheritance through the class keyword.


How do you define a class in JavaScript?

You can define a class using the class keyword followed by the class name and a body containing the constructor and methods.


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

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

const alice = new Person('Alice', 30);
alice.greet(); // Hello, my name is Alice and I am 30 years old.

What is a constructor in a class?

A constructor is a special method called when an instance of a class is created. It is used to initialize properties and set up the object.


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

const dog = new Animal('Rex');
console.log(dog.name); // Rex

How do you create methods in a class?

Methods can be defined directly inside the class body without the function keyword. They become part of the class prototype.


class Dog {
  bark() {
    console.log('Woof!');
  }
}

const myDog = new Dog();
myDog.bark(); // Woof!

What is inheritance in the context of classes?

Inheritance allows one class to inherit properties and methods from another class, promoting code reuse. In JavaScript, this is achieved using the extends keyword.


class Animal {
  speak() {
    console.log('Animal speaks');
  }
}

class Dog extends Animal {
  speak() {
    console.log('Dog barks');
  }
}

const dog = new Dog();
dog.speak(); // Dog barks

What is the super keyword and how is it used?

The super keyword is used to call the constructor and methods of a parent class. It must be called before using this in a derived class constructor.


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

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

class Cat extends Animal {
  constructor(name) {
    super(name); // Call the parent class constructor
  }

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

const cat = new Cat('Whiskers');
cat.speak(); // Whiskers meows.

How do you create static methods in a class?

Static methods are defined using the static keyword and are called on the class itself, not on instances of the class.


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

console.log(MathUtil.add(5, 3)); // 8

What are private fields in JavaScript classes?

Private fields are properties that are only accessible within the class they are defined in. They are declared using the # prefix.


class BankAccount {
  #balance; // Private field

  constructor(initialBalance) {
    this.#balance = initialBalance;
  }

  deposit(amount) {
    this.#balance += amount;
  }

  getBalance() {
    return this.#balance; // Accessing private field
  }
}

const account = new BankAccount(100);
account.deposit(50);
console.log(account.getBalance()); // 150
// console.log(account.#balance); // SyntaxError: Private field '#balance' must be declared in an enclosing class

What is the difference between class methods and instance methods?

Class methods (static methods) are called on the class itself and do not have access to instance properties or methods. Instance methods are called on instances of the class and have access to instance properties via this.


class MyClass {
  static classMethod() {
    console.log('I am a class method.');
  }

  instanceMethod() {
    console.log('I am an instance method.');
  }
}

MyClass.classMethod(); // I am a class method.

const myInstance = new MyClass();
myInstance.instanceMethod(); // I am an instance method.

Can you explain method overriding in JavaScript classes?

Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its parent class. This allows the subclass to modify or extend the behavior of the parent class method.


class Animal {
  speak() {
    console.log('Animal speaks');
  }
}

class Cat extends Animal {
  speak() {
    console.log('Cat meows');
  }
}

const animal = new Animal();
animal.speak(); // Animal speaks

const cat = new Cat();
cat.speak(); // Cat meows
Ads