Basics

A class is a template for creating objects. It defines the properties and methods that will be shared by all objects created from the class. Here is a simple example of a class in JavaScript:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  sayHello() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

const person1 = new Person('John', 30);
const person2 = new Person('Jane', 28);

person1.sayHello(); // "Hello, my name is John and I am 30 years old."
person2.sayHello(); // "Hello, my name is Jane and I am 28 years old."

In this example, we define a class called Person with a constructor function that is used to create new objects from the class. The constructor function takes two arguments, name and age, and sets them as properties of the new object. The class also has a sayHello method that logs a greeting to the console.

We can then create new objects from the Person class using the new keyword and the Person constructor function. Each object created from the class will have its own unique properties, but they will all share the same methods defined in the class.

Last updated