JavaScript Classes

ECMAScript 2015, also known as ES6, introduced JavaScript classes.

JavaScript class is a template for JavaScript objects.

of JavaScript class

Syntax

Use the keyword class Create a class.

Always add a method named constructor() method:

Syntax

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

instance

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

The above example creates a class named "Car".

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

JavaScript ClassesNotobject.

It is just a JavaScript object'stemplate.

Using a class

If you have a class, you can use it to create objects:

instance

let myCar1 = new Car("Ford", 2014);
let myCar2 = new Car("Audi", 2019);

Try It Yourself

The above example uses Car classtwo were created Car object.

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

Constructor Method

Constructor method is a special method:

  • It must have the exact name of "constructor"
  • Automatically executed when a new object is created
  • Used to initialize object properties
  • If the constructor method is not defined, JavaScript will add an empty constructor method.

Class Methods

Creating class methods

Syntax

same as object methods.

Use the keyword class Create a class.

Always add constructor() Methods.

Then add any number of methods.

Syntax

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

Create a class method named "age" that returns the car's age:

instance

class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }
  age() {
    let date = new Date();
    return date.getFullYear() - this.year;
  }
}
let myCar = new Car("Ford", 2014);
document.getElementById("demo").innerHTML = "My car is " + myCar.age() + " years old.";

Try It Yourself

You can send parameters to class methods:

instance

class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }
  age(x) {
    return x - this.year;
  }
}
let date = new Date();
let year = date.getFullYear();
let myCar = new Car("Ford", 2014);
document.getElementById("demo").innerHTML = "My car is " + myCar.age(year) + " years old.";

Try It Yourself

Browser Support

The following table lists the first browser version to fully support JavaScript classes:

Chrome IE Firefox Safari Opera
Chrome 49 Edge 12 Firefox 45 Safari 9 Opera 36
March 2016 July 2015 March 2016 October 2015 March 2016

In the latter part of this tutorial, you will learn more about JavaScript classes.