JavaScript Class


A class encapsulates data and behavior into a single unit, making it easier to write and maintain complex programs. Classes provide a way to define objects with a consistent interface and behavior, making it easier to write reusable code.

In JavaScript, classes were introduced in ECMAScript 6 (ES6) and are a powerful new feature. a class is a blueprint for creating objects that share the same properties and methods. A class defines a new data type, which can be used to create instances of that type.

Real World Examples of Class

Classes are a fundamental concept in object-oriented programming, and they are used in many real-world applications. Here are a few examples of how classes are used in real-world scenarios:

  1. Banking system -  A banking system might use classes to represent different types of accounts, such as checking accounts, savings accounts, and credit card accounts. Each class would contain properties such as the account balance and account holder information, as well as methods for depositing and withdrawing funds.
  2. E-commerce website - An e-commerce website might use classes to represent different types of products, such as clothing, electronics, and books. Each class would contain properties such as the product price and description, as well as methods for adding items to a shopping cart and checking out.
  3. Social media platform - A social media platform might use classes to represent different types of users, such as regular users, moderators, and administrators. Each class would contain properties such as the user's name and profile information, as well as methods for posting content and managing user accounts.

In each of these examples, classes provide a way to encapsulate data and behavior into a single unit, making it easier to write and maintain complex code. Classes also offer features such as inheritance and polymorphism, which help reduce duplication and increase code reuse.

Advantage of Class in JavaScript

Classes are a powerful feature in JavaScript that offer several advantages for building complex applications:

  1. Abstraction - Classes allow you to encapsulate data and behavior into a single unit, hiding the details of how the class works from the rest of the program. This makes it easier to write and maintain complex code by breaking it down into smaller, more manageable pieces.
  2. Inheritance - Classes allow you to create new classes based on existing classes, inheriting their properties and behavior. This makes it easier to reuse existing code and build on top of it, reducing duplication and increasing code reuse.
  3. Polymorphism - Classes allow you to define objects with a consistent interface and behavior, making it easier to write code that works with many different types of objects. This makes your code more flexible and adaptable to changing requirements.
  4. Encapsulation - Classes allow you to protect data and behavior by making them private or protected. This can help prevent bugs and improve the reliability of your code.
  5. Code organization - Classes provide a way to organize code into logical units, making it easier to understand and maintain. This can help reduce complexity and improve code readability.

Overall, classes are a powerful tool for building complex JavaScript applications. They provide a way to encapsulate data and behavior into a single unit, making it easier to write and maintain code. They also offer features like inheritance and polymorphism, which help reduce duplication and increase code reuse.

Disadvantage of Class in JavaScript

While classes are a powerful feature in JavaScript, there are also some potential disadvantages to using them:

  1. Complexity - Classes can add complexity to code, especially when used improperly. Classes can also introduce new concepts such as inheritance and polymorphism, which may be difficult for beginners to understand.
  2. Overengineering - Classes can be overused in cases where simpler solutions would suffice. Overengineering can lead to unnecessary complexity and reduce code readability.
  3. Performance - Classes can impact performance, especially when creating and manipulating large numbers of objects. Creating objects with classes can be slower than creating objects with other techniques such as object literals.
  4. Backward compatibility - Classes were introduced in ECMAScript 6 (ES6), which means that code using classes may not be compatible with older browsers or environments that do not support ES6 features.
  5. Prototypes - Classes in JavaScript are built on top of the prototype-based inheritance model, which can be confusing for developers who are used to class-based inheritance in other programming languages.

Overall, while classes can offer many advantages, they should be used judiciously and with an understanding of their potential drawbacks. It's important to weigh the benefits and costs of using classes in each particular case and to consider alternative approaches when appropriate.

Here's an example of a simple JavaScript class that represents a book:

class Book {
  constructor(title, author, pages) {
    this.title = title;
    this.author = author;
    this.pages = pages;
  }
}

In this example, the Book class has a constructor method that takes three parameters (title, author, and pages) and assigns them to properties of the class. The class also has a toString method, which returns a string representation of the book.

The Constructor Method

The constructor method is a special method:

  • It has to have the exact name "constructor"
  • It is executed automatically when a new object is created
  • It is used to initialize object properties

 To create an instance of the Book class, you would use the new keyword followed by the name of the class and any necessary arguments:

 let myBook = new Book("JavaScript Functions Book", "Rohatash", 2000);
 document.write("Book Title is: "+ myBook.title.toString() +"");
 document.write("Author name is: " + myBook.author.toString() + "");
 document.write("Total Pages: "+myBook.pages.toString()); 

In this example, we create a new instance of the Book class with the title "JavaScript Functions Book", author "Rohatash", and 20000 pages. We then call the toString method on this instance, which returns a string representation of the book. Classes in JavaScript provide a powerful and flexible way to define new data types and create objects with consistent interfaces and behaviors. They are an essential tool for building complex JavaScript applications.

Example

Here's an example of a simple JavaScript class that represents a book and call that class with new keyword.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h2>TutorialsTrend - JavaScript Class Example</h2>
<script>
class Book {
  constructor(title, author, pages) {
  this.title = title;
  this.author = author;
  this.pages = pages;
  }
}
let myBook = new Book("JavaScript Functions", "Rohatash", 2000);
document.write("Book Title is: "+ myBook.title.toString() +"</br>");
document.write("Author name is: " + myBook.author.toString() + "</br>");
document.write("Total Pages: "+myBook.pages.toString()); 
</script>
</body>
</html>

Output

Image1

Inheritance with JavaScript Classes

Inheritance is a fundamental feature of object-oriented programming that allows you to create new classes based on existing classes, inheriting their properties and methods. In JavaScript, inheritance is implemented using the extends keyword.

Here's an example of how inheritance works with classes in JavaScript:

class Animal {
  constructor(name) {
  this.name = name;
}
speak() {
   console.log(`${this.name} makes a noise.`);
  }
}
class Dog extends Animal {
speak() {
    console.log(`${this.name} barks.`);
  }
}

let myDog = new Dog("Rufus");
myDog.speak(); // Output: "Rufus barks."

In this example, we have two classes: Animal and Dog. The Animal class has a constructor that takes a name parameter and a speak method that logs a message to the console. The Dog class extends the Animal class using the extends keyword and overrides the speak method to log a different message to the console.

We then create a new instance of the Dog class called myDog with the name "Rufus" and call the speak method on it. Since the Dog class overrides the speak method, it logs the message "Rufus barks." to the console.

In this way, inheritance allows you to create new classes based on existing classes, inheriting their properties and methods while also adding new functionality. This makes it easier to write and maintain complex JavaScript code by reusing existing code and building on top of it.


Prev Next