Javascript

Learn About Javascript Classes with Examples For Beginners

Learn About Javascript Classes with Examples For Beginners

For a long time, developers used constructor functions and prototypes to create objects. ES6 introduced classes — a cleaner, more intuitive syntax for creating and working with objects. This article explains what JavaScript classes are, how to use them, and includes practical examples.

 

 

Most of us have used the constructor functions to create an object of specific type. The constructor function is simply a function, but when used with the new and this keyword, it becomes a constructor function:

function Person(first, last, age) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
}

const person1 = new Person("Wael", "Salah", 33);
const person2 = new Person("John", "Doe", 40);

In ES6 this example can be rewritten using a class (the new syntax).

 

🔹 What is a JavaScript Class?

A class in JavaScript is essentially a template for creating objects. It encapsulates data (properties) and behavior (methods). While classes use a new syntax, they’re still based on JavaScript’s prototype system under the hood.

🔹 Basic Syntax

class ClassName {
  constructor(parameter1, parameter2) {
    // Initialize properties
    this.property1 = parameter1;
    this.property2 = parameter2;
  }

  // Method
  methodName() {
    console.log(`Property1 is ${this.property1}`);
  }
}

Like any object oriented programming language, the same rules applied to classes in javascript. The class can contain properties, methods, constructor, getters, setters and static properties.

  • constructor() is a special method called automatically when a new object is created.

  • Other methods inside the class become part of the object’s prototype.

🔹 Example 1: A Simple Car Class

class Car {
  constructor(brand, model) {
    this.brand = brand;
    this.model = model;
  }

  start() {
    console.log(`${this.brand} ${this.model} is starting...`);
  }

  stop() {
    console.log(`${this.brand} ${this.model} is stopping.`);
  }
}

// Creating objects
const car1 = new Car('Toyota', 'Corolla');
const car2 = new Car('Tesla', 'Model 3');

car1.start(); // Output: Toyota Corolla is starting...
car2.stop();  // Output: Tesla Model 3 is stopping.

Here:

  • Car is the class.

  • car1 and car2 are objects (instances) created from the class.

  • start() and stop() are methods.

 

🔹 Example 2: Class Inheritance

Classes can extend other classes to create hierarchies with the extend keyword. This is called inheritance.

class Vehicle {
  constructor(brand) {
    this.brand = brand;
  }

  move() {
    console.log(`${this.brand} is moving.`);
  }
}

class Bike extends Vehicle {
  constructor(brand, type) {
    super(brand); // Call parent constructor
    this.type = type;
  }

  info() {
    console.log(`${this.brand} bike is a ${this.type} type.`);
  }
}

const bike1 = new Bike('Yamaha', 'Sport');
bike1.move(); // Yamaha is moving.
bike1.info(); // Yamaha bike is a Sport type.

Key points:

  • extends creates a subclass.

  • super() calls the parent class’s constructor.

 

🔹 Example 3: Getters and Setters

You can define getters and setters in classes to control how properties are read and updated.

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

  get area() {
    return this._width * this._height;
  }

  set width(newWidth) {
    this._width = newWidth;
  }
}

const rect = new Rectangle(10, 5);
console.log(rect.area); // 50
rect.width = 20;
console.log(rect.area); // 100

 

🔹 Example 4: Static Methods

Static methods belong to the class itself, not its instances. An example is the built-in Math object.

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

console.log(MathUtils.add(5, 10)); // 15

You call static methods directly on the class, not on an instance.

 

🔹 Key Points to Remember

  • Classes in JavaScript are syntactic sugar over prototype-based inheritance.

  • Use constructor() to initialize properties.

  • Use extends and super() for inheritance.

  • Use getters and setters for computed properties.

  • Use static methods for utility functions related to the class but not to a particular instance.

 

 

0 0 votes
Article Rating

What's your reaction?

Excited
0
Happy
0
Not Sure
0
Confused
0

You may also like

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments