DEV Community

Cover image for How to define and use of a class in Javascript.
Shamsul huda
Shamsul huda

Posted on

How to define and use of a class in Javascript.

Classes in JavaScript are used to create objects that are instances of the same blueprint. A class is essentially a blueprint for creating objects, and it can include properties and methods that define the characteristics and behavior of those objects.

Here's an example of how to define a class in JavaScript:

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.`);
  }
}
Enter fullscreen mode Exit fullscreen mode

In the example above, the Person class has a constructor method that is used to initialize the objects created from the class. The constructor method takes two arguments, name and age, which are used to set the name and age properties of the object.

The Person class also has a greet method that logs a greeting message to the console.

To create an object from the Person class, we use the new operator followed by the class name:

let person = new Person('John Doe', 30);
person.greet();
Enter fullscreen mode Exit fullscreen mode

This will create a new object with the name John Doe and the age 30, and it will log the following message to the console:

Hello, my name is John Doe and I am 30 years old.
Enter fullscreen mode Exit fullscreen mode

It's worth noting that classes in JavaScript are just a syntax sugar for the prototype-based object-oriented programming model that is native to JavaScript. You can achieve similar functionality to classes using prototypes and constructor functions. However, the class syntax provides a cleaner and more intuitive syntax for defining objects and their properties and methods.

Top comments (0)