JavaScript Classes


In 2015, ECMAScript, or ES6, brought in something called JavaScript Classes.

JavaScript Classes are templates for JavaScript Objects.

JavaScript Class Syntax

Employ the term class to establish a class.

Always include a method called constructor():

Syntax

class ClassName {
  constructor() { ... }
}

Example

class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }
}

The code above makes a class called "Car."

The class initially has two properties: "name" and "year."

A JavaScript class is different from an object.

It's a pattern for JavaScript objects.


Using a Class

When you have a class, you can use it to make things called objects:

The example above uses the Car class to make two Car objects.

The constructor method gets automatically activated when a new object is made.


The Constructor Method

The constructor method is a unique function:

  • Ensure that the name "constructor" is precisely used.
  • It runs on its own whenever a new object is made.
  • It is employed to set up the characteristics of an object.

If you don't create a constructor method, JavaScript will automatically include an empty constructor method.


Class Methods

Methods within a class are formed using the identical structure as methods within an object.

Employ the term class to establish a class.

Make sure to include a constructor() method at all times.

Afterward, include as many methods as needed.

Syntax

class ClassName {
  constructor() { ... }
  method_1() { ... }
  method_2() { ... }
  method_3() { ... }
}

Create a class method called "age" that gives back the age of the car.

You can provide information to class methods.