JavaScript(ES6) Class

Muhammad Hassan
3 min readMar 5, 2021

JavaScript’s “classes” aren’t anything like classes in Java, Python, or Really, any other object-oriented language you’re likely to have used.

Classes in JavaScript are in fact “special functions”, and just as you can define function expressions and function declarations, the class syntax has two components: class expressions and class declarations.

A JavaScript class is a blueprint for creating objects. A class encapsulates data and functions that manipulate the data.

Unlike other programming languages such as Java and C++, JavaScript classes are syntactic sugar over the prototypal inheritance. In other words, ES6 classes are just special functions.

Prior to ES6, JavaScript had no concepts of classes. To mimic a class, we often used a constructor function as shown in the following example:

function Person(name) {
this.name = name;
}

Person.prototype.getName = function () {
return this.name;
};

var john = new Person("John Doe");
console.log(john.getName());
Output: John Doe

ES6 class declaration

You create classes with the class keyword, followed by an identifier, and finally, a code block called the class body. These are called class declarations.

class Person {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}

This Person class behaves like the Person type in the previous example. However, instead of using a constructor function, it uses the class keyword.

In the Person class, the constructor() is where you can initialize the properties of an instance. JavaScript automatically calls the constructor() method when you instantiate an object of the class.

The following creates a new Person object, which will automatically call the constructor() of the Person class.

  • Classes can only contain method definitions, not data properties;
  • When defining methods, you use shorthand method definitions;
  • Unlike when creating objects, you do not separate method definitions in class bodies with commas; and
  • You can refer to properties on instances of the class directly (Line A).

A distinctive feature of classes is the function called a constructor. This is where you initialize your object’s properties.

You don’t have to define a constructor function. If you choose not to, the engine will insert an empty one for you.

Benefits of Using class

  • Convenient, self-contained syntax.
  • A single, canonical way to emulate classes in JavaScript. Prior to ES6, there were several competing implementations in popular libraries.
  • More familiar to people from a class-based language background.

Resources:

--

--