Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS Classes

ECMAScript 2015 (ES6) introduced JavaScript Classes, which serve as templates for creating JavaScript objects.

JavaScript Class Syntax

Use the class keyword to define a class, and always include a constructor() method.

Syntax

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

Example

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

The example above defines a class called “Car,” which has two initial properties: “name” and “year.”

A JavaScript class is not an object; it is a blueprint or template for creating JavaScript objects.

Using a Class

Once you have a class, you can use it to create objects.

Example

const myCar1 = new Car(“Ford”2014);
const myCar2 = new Car(“Audi”2019);

The example above uses the Car class to create two instances of the Car object.

The constructor method is called automatically when a new object is instantiated.

The Constructor Method

The constructor method is a special method that:

  • Must be named exactly “constructor”.
  • Is executed automatically when a new object is created.
  • Is used to initialize the object’s properties.
  • If not defined, JavaScript automatically provides an empty constructor.

Class Methods

Class methods are defined using the same syntax as object methods.

 

To create a class, use the class keyword.

 

Always include a constructor() method.

 

After that, you can add any number of methods to the class.

Syntax

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

Create a class method called age that returns the age of the car.

Example

class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }
  age() {
    const date = new Date();
    return date.getFullYear() – this.year;
  }
}

const myCar = new Car(“Ford”2014);
document.getElementById(“demo”).innerHTML =
“My car is “ + myCar.age() + ” years old.”;

You can pass parameters to class methods.

Example

class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }
  age(x) {
    return x – this.year;
  }
}

const date = new Date();
let year = date.getFullYear();

const myCar = new Car(“Ford”2014);
document.getElementById(“demo”).innerHTML=
“My car is “ + myCar.age(year) + ” years old.”;

Browser Support

The following table lists the first browser version that fully supports classes in JavaScript.

js 5

You will learn much more about JavaScript classes later in this tutorial.