THE WORLD'S LARGEST WEB DEVELOPER SITE

JS Tutorial

JS HOME JS Introduction JS Where To JS Output JS Statements JS Syntax JS Comments JS Variables JS Operators JS Arithmetic JS Assignment JS Data Types JS Functions JS Objects JS Events JS Strings JS String Methods JS Numbers JS Number Methods JS Arrays JS Array Methods JS Array Sort JS Array Iteration JS Dates JS Date Formats JS Date Get Methods JS Date Set Methods JS Math JS Random JS Booleans JS Comparisons JS Conditions JS Switch JS Loop For JS Loop While JS Break JS Type Conversion JS Bitwise JS RegExp JS Errors JS Scope JS Hoisting JS Strict Mode JS this Keyword JS Let JS Const JS Arrow Function JS Classes JS Debugging JS Style Guide JS Best Practices JS Mistakes JS Performance JS Reserved Words JS Versions JS Version ES5 JS Version ES6 JS JSON

JS Forms

JS Forms Forms API

JS Objects

Object Definitions Object Properties Object Methods Object Accessors Object Constructors Object Prototypes Object ECMAScript 5

JS Functions

Function Definitions Function Parameters Function Invocation Function Call Function Apply Function Closures

JS HTML DOM

DOM Intro DOM Methods DOM Document DOM Elements DOM HTML DOM CSS DOM Animations DOM Events DOM Event Listener DOM Navigation DOM Nodes DOM Collections DOM Node Lists

JS Browser BOM

JS Window JS Screen JS Location JS History JS Navigator JS Popup Alert JS Timing JS Cookies

JS AJAX

AJAX Intro AJAX XMLHttp AJAX Request AJAX Response AJAX XML File AJAX PHP AJAX ASP AJAX Database AJAX Applications AJAX Examples

JS JSON

JSON Intro JSON Syntax JSON vs XML JSON Data Types JSON Parse JSON Stringify JSON Objects JSON Arrays JSON PHP JSON HTML JSON JSONP

JS vs jQuery

jQuery Selectors jQuery HTML jQuery CSS jQuery DOM

JS Examples

JS Examples JS HTML DOM JS HTML Input JS HTML Objects JS HTML Events JS Browser JS Exercises JS Quiz JS Certificate

JS References

JavaScript Objects HTML DOM Objects


JavaScript Classes


ECMAScript 2015

ES6, also known as ECMAScript2015, introduced classes.

A class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class, and the properties are assigned inside a constructor() method.


Class Definition

Use the keyword class to create a class, and always add the constructor() method.

The constructor method is called each time the class object is initialized.

Example

A simple class definition for a class named "Car":

class Car {
  constructor(brand) {
    this.carname = brand;
  }
}

Now you can create objects using the Car class:

Example

Create an object called "mycar" based on the Car class:

class Car {
  constructor(brand) {
    this.carname = brand;
  }
}
mycar = new Car("Ford");

Try it Yourself »

Note: The constructor method is called automatically when the object is initialized.


Methods

The constructor method is special, it is where you initialize properties, it is called automatically when a class is initiated, and it has to have the exact name "constructor", in fact, if you do not have a constructor method, JavaScript will add an invisible and empty constructor method.

You are also free to make your own methods, the syntax should be familiar:

Example

Create a method named "present":

class Car {
  constructor(brand) {
    this.carname = brand;
  }
  present() {
    return "I have a " + this.carname;
  }
}

mycar = new Car("Ford");
document.getElementById("demo").innerHTML = mycar.present();

Try it Yourself »

As you can see in the example above, you call the method by referring to the object's method name followed by parentheses (any parameters would go inside the parentheses).

Example

Send a parameter to the "present()" method:

class Car {
  constructor(brand) {
    this.carname = brand;
  }
  present(x) {
    return x + ", I have a " + this.carname;
  }
}

mycar = new Car("Ford");
document.getElementById("demo").innerHTML = mycar.present("Hello");

Try it Yourself »



Static Methods

Static methods are defined on the class itself, and not on the prototype.

That means you cannot call a static method on the object (mycar), but on the class (Car):

Example

Create a static method and call it on the class:

class Car {
  constructor(brand) {
    this.carname = brand;
  }
  static hello() {
    return "Hello!!";
  }
}

mycar = new Car("Ford");

//Call 'hello()' on the class Car:
document.getElementById("demo").innerHTML = Car.hello();

//and NOT on the 'mycar' object:
//document.getElementById("demo").innerHTML = mycar.hello();
//this would raise an error.

Try it Yourself »

If you want to use the mycar object inside the static method, you can send it as a parameter:

Example

Send "mycar" as a parameter:

class Car {
  constructor(brand) {
    this.carname = brand;
  }
  static hello(x) {
    return "Hello " + x.carname;
  }
}

mycar = new Car("Ford");

document.getElementById("demo").innerHTML = Car.hello(mycar);

Try it Yourself »


Inheritance

To create a class inheritance, use the extends keyword.

A class created with a class inheritance inherits all the methods from another class:

Example

Create a class named "Model" which will inherit the methods from the "Car" class:

class Car {
  constructor(brand) {
    this.carname = brand;
  }
  present() {
    return 'I have a ' + this.carname;
  }
}

class Model extends Car {
  constructor(brand, mod) {
    super(brand);
    this.model = mod;
  }
  show() {
    return this.present() + ', it is a ' + this.model;
  }
}

mycar = new Model("Ford", "Mustang");
document.getElementById("demo").innerHTML = mycar.show();

Try it Yourself »

The super() method refers to the parent class.

By calling the super() method in the constructor method, we call the parent's constructor method and gets access to the parent's properties and methods.

Inheritance is useful for code reusability: reuse properties and methods of an existing class when you create a new class.


Getters and Setters

Classes also allows you to use getters and setters.

It can be smart to use getters and setters for your properties, especially if you want to do something special with the value before returning them, or before you set them.

To add getters and setters in the class, use the get and set keywords.

Example

Create a getter and a setter for the "carname" property:

class Car {
  constructor(brand) {
    this.carname = brand;
  }
  get cnam() {
    return this.carname;
  }
  set cnam(x) {
    this.carname = x;
  }
}

mycar = new Car("Ford");

document.getElementById("demo").innerHTML = mycar.cnam;

Try it Yourself »

Note: even if the getter is a method, you do not use parentheses when you want to get the property value.

The name of the getter/setter method cannot be the same as the name of the property, in this case carname.

Many programmers use an underscore character _ before the property name to separate the getter/setter from the actual property:

Example

You can use the underscore character to separate the getter/setter from the actual property:

class Car {
  constructor(brand) {
    this._carname = brand;
  }
  get carname() {
    return this._carname;
  }
  set carname(x) {
    this._carname = x;
  }
}

mycar = new Car("Ford");

document.getElementById("demo").innerHTML = mycar.carname;

Try it Yourself »

To use a setter, use the same syntax as when you set a property value, without parentheses:

Example

Use a setter to change the carname to "Volvo":

class Car {
  constructor(brand) {
    this._carname = brand;
  }
  get carname() {
    return this._carname;
  }
  set carname(x) {
    this._carname = x;
  }
}

mycar = new Car("Ford");
mycar.carname = "Volvo";
document.getElementById("demo").innerHTML = mycar.carname;

Try it Yourself »


Hoisting

Unlike functions, and other JavaScript declarations, class declarations are not hoisted.

That means that you must declare a class before you can use it:

Example

//You cannot use the class yet.
//mycar = new Car("Ford")
//This would raise an error.

class Car {
  constructor(brand) {
    this.carname = brand;
  }
}

//Now you can use the class:
mycar = new Car("Ford")
Try it Yourself »

Note: For other declarations, like functions, you will NOT get an error when you try to use it before it is declared, because the default behavior of JavaScript declarations are hoisting (moving the declaration to the top).


"use strict"

The syntax in classes must be written in "strict mode".

You will get an error if you do not follow the "strict mode" rules.

Example

In "strict mode" you will get an error if you use a variable without declaring it:

class Car {
  constructor(brand) {
    i = 0;
    this.carname = brand;
  }
}
var mycar = new Car("Ford");
Try it Yourself »

Learn more about "strict mode" in our JavaScript Strict Mode chapter.


Browser Support

The following table defines the first browser version with full support for Classes in JavaScript:

Chrome 49 Edge 12 Firefox 45 Safari 9 Opera 36
Mar, 2016 Jul, 2015 Mar, 2015 Oct, 2015 Mar, 2016