javascript
  1. javascript-class

JavaScript Class

JavaScript classes are the blueprint for creating objects with predefined properties and methods.

Syntax

To create a class in JavaScript, we use the class keyword followed by the class name and the body of the class.

class ClassName {
  // properties and methods
}

To create an object of the class, we use the new keyword followed by the class name and any arguments passed to the constructor method.

let objectName = new ClassName(arguments);

Example

Let's create a simple class Person with two properties, name and age, and a method greet.

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  greet() {
    console.log(`Hi, my name is ${this.name} and I'm ${this.age} years old.`);
  }
}

Now, let's create an object john of the Person class and call the greet method.

let john = new Person('John', 25);
john.greet();

Output

The output of the above example would be:

Hi, my name is John and I'm 25 years old.

Explanation

In the above example, we created a class Person with two properties, name and age, and a method greet. The constructor() method is called when an object of the class is created and initializes the properties of the object.

We then created an object john of the Person class with name as 'John' and age as 25 using the new keyword and called the greet method on the object.

Use

JavaScript classes are used in object-oriented programming to define objects and their behavior. They provide an efficient and organized way to create and manage objects with the same properties and methods.

Important Points

  • A class can have properties and methods.
  • The constructor() method is called when an object of the class is created and initializes the properties of the object.
  • We create an object of the class using the new keyword followed by the class name and any arguments passed to the constructor method.

Summary

JavaScript classes are the blueprint for creating objects with predefined properties and methods. We use the class keyword followed by the class name and the body of the class to create a class. A class can have properties and methods. The constructor() method is called when an object of the class is created and initializes the properties of the object. We create an object of the class using the new keyword followed by the class name and any arguments passed to the constructor method.

Published on: