Classes were introduced in ECMAScript 2015 aka ES6.
Class and object concepts are well known from many programming language like PHP, Java, Python with some minor alterations. Classes allow us to do less typing which is one of the biggest advantage too.
Classes in JavaScript are not actual objects but templates for Objects.
JavaScript Class Syntax
The basics of the class starts from the syntax. To create a class in JavaScript, we use the class keyword.
Remember to add a constructor() method when you create a class. It will be called spontaneously when a new object is created.
You have to use the exact keyword “constructor” to create it. If you don’t create it then JavaScript will add an empty constructor method.
This is how the syntax looks like:
class ClassName {
constructor() {
...
...
}
}
Examples
How to create a class in JavaScript?
Let’s create a class to understand how it works.
class Person {
constructor(name, birthDate) {
this.name = name;
this.birthDate = birthDate;
}
}
In the simple example above, we have a class named as Person. The properties we define in the constructor method are called the initial properties. We have two initial properties set, name and birthDate.
You need to declare your class first and then try to access it, or you will get a ReferenceError, which is called hoisting.
Since we have the template ready for objects, we can create as many objects as we want.
How to create objects from a class in JavaScript?
To create an object from the class, we need to use the keyword new followed by the class name and we also need to pass the initial properties in the class parameters.
Let’s create a few objects.
person1 = new Person("Josh", "01/01/1991");
person2 = new Person("Jim","12/05/1991");
person3 = new Person("Kim", "12/05/1991");
We just created 3 objects as person1, person2 and person3 from the class Person.
We can make this example as complex as it can be! For instance, we can create a complex employee system where each new employees will have same initial properties. Then we can create new employee object each time we need. We’ll see how to add some advanced properties and methods to some employees only and not all. That way we can have a hierarchical structure of an office.
How to print data using a class and it’s objects?
Once we create any object we can access it’s features by using the object name and dot operator followed by the property name.
See it in action here:
How to create class methods?
A class can have any number of methods. All we need to do is add methods after the main constructor method.
Kinda like this syntax:
class ClassName {
constructor() {
...
...
}
method_x(){
...
}
method_y(){
...
}
}
Class Method Example
Let’s add a method names role() that will set the role for the objects we create.
class examples guide object-oriented objects