Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

JavaScript - Classes and Object-Oriented Programming

Classes and Object-Oriented Programming

Classes and Object-Oriented Programming (OOP) are fundamental concepts in JavaScript and many other programming languages. They provide a way to organize and structure code around objects and their interactions. Here's an introduction to classes and OOP in JavaScript:

Classes:

A class is a blueprint for creating objects with a predefined structure and behavior. It defines the properties (attributes) and methods (functions) that the objects created from it will have.

Creating a Class:

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  sayHello() {
    console.log(`Hello, my name is ${this.firstName} ${this.lastName}.`);
  }
}
 

Creating Objects (Instances):

let johnDoe = new Person('John', 'Doe');
let janeDoe = new Person('Jane', 'Doe');

johnDoe.sayHello(); // Output: "Hello, my name is John Doe."
janeDoe.sayHello(); // Output: "Hello, my name is Jane Doe."
 

Constructor and this Keyword:

The constructor method is a special method that gets called when a new object is created from a class. It is used to initialize the object's properties.

Inheritance:

Inheritance is a key concept in OOP that allows a class to inherit properties and methods from another class. The class that is inherited from is called the parent or superclass, and the class that inherits is called the child or subclass.

Extending a Class:

class Student extends Person {
  constructor(firstName, lastName, studentId) {
    super(firstName, lastName); // Call the parent class's constructor
    this.studentId = studentId;
  }

  sayHello() {
    console.log(`Hello, I'm a student. My name is ${this.firstName} ${this.lastName}.`);
  }
}
 

Encapsulation, Abstraction, Polymorphism:

  • Encapsulation: Encapsulation is the bundling of data and the methods that operate on that data, restricting access to some of the object's components.
  • Abstraction: Abstraction involves hiding the complexity of an object and only showing the necessary features.
  • Polymorphism: Polymorphism allows objects to be treated as instances of their parent class, even if they are actually instances of a subclass.

Static Methods:

Static methods belong to the class rather than any specific instance. They are often used for utility functions that don't depend on specific instance properties.

class Calculator {
  static add(x, y) {
    return x + y;
  }

  static multiply(x, y) {
    return x * y;
  }
}