In this tutorial, you’ll learn what are classes in JavaScript and how to use classes in JavaScript. This tutorial assumes the reader to have a basic knowledge of JavaScript.
Getting Started With Classes In JavaScript
You can use the traditional JavaScript functional declaration to create objects in JavaScript. Here is an example showing the same:
function Employee(fname, lname){
this.firstName = fname;
this.lastName = lname;
}
Employee.prototype.getFullName = function() {
return this.firstName + ' ' + this.lastName;
}
const emp = new Employee('roy','sam');
console.log(emp.getFullName());
As seen in the above code, you have defined a functional declaration for Employee and added a prototype method called getFullName. The problem with the above code is that the functional declaration is hoisted.
In ES 6 classes were introduced which provided a more concise syntax. You can declare a class using the class keyword. Let’s see how to create a class for an employee.
class Employee{
constructor(fname, lname){
this.fname = fname;
this.lname = lname;
}
getFullName(){
return this.fname + ' ' + this.lname;
}
}
const emp = new Employee('Michael','Jordan');
console.log(emp.getFullName());
Static Methods In Classes In JavaScript
You use static methods often for creating utility functions. Static methods can be accessed without
instantiating the class. static keyword is used to declare a static method in JavaScript. Here is an example of static methods in JavaScript :
class Employee{
constructor(fname, lname){
this.fname = fname;
this.lname = lname;
}
getFullName(){
return this.fname + ' ' + this.lname;
}
static getTenTimes(a){
return a * 10;
}
}
console.log(Employee.getTenTimes(10));
As seen in the above code, you have not created an instance of the class Employee. Instead you have directly called the static method getTenTimes. Since getTenTimes being a static method the constructor won’t be called.
Wrapping It Up
In this tutorial, you learnt what are classes in JavaScript. You learnt how to create a class in JavaScript and why classes are better than functional declarations. You also learn about static methods in classes.
Have you used classes in JavaScript ? How was your experience ? Do let us know your thoughts in the comments below.