What Are Javascript Classes and How to Use Them
What are javascript classes
Classes are a fundamental concept in object-oriented programming, and they are used in many programming languages, but it wasn’t like this in Javascript. Until ECMAScript2015, known as ES6, classes didn’t exist in JS. In 2015 with the update classes were introduced as syntactic sugar for the existing prototype inheritance model. What classes bring is a more comfortable and more readable syntax for objects and inheritance.
Class in Javascript is a type of function, but instead of initializing it with the function keyword, the class keyword is used.
In this article, I’ll try to provide an introduction to what classes are and how we can use them. It will explain:
- defining classes,
- constructor method,
- defining methods,
- extending classes and super keyword,
- getters and setters.
Let’s start!
* To check the code execution open the console in the browser and try to execute the code ( if you are using Google Chrome right-click on the page and select Investigate)
1. Defining classes
To define a class, we have to start from a class keyword, followed by the name of the class, then curly braces after the name. Next, inside the defined class, we set a constructor with properties assigned, which is called whenever a class is initialized. Let’s take a look at a code example:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
In the code example above, the class Person is defined, with the constructor, where we set name and age properties. To initialize this class, we have to use a new keyword with the class name, and parameters like it work with the object. Let’s see the code example:
var person = new Person("Peter", 25);
In the code above we initialized a class with two parameters, name= “Peter” and age= “25” and assigned it to the variable person.
What is worth to mention, although classes are functions, hoisting doesn’t work in this case. It means that every class has to be defined first and initialized next. Otherwise, the Reference Error will appear. Also, it’s good to remember that code inside the class is in ‚strict mode’. It will throw more errors and help us to avoid mistyping or syntax errors.
2. Constructor method
While defining a class, we used a constructor. Now let’s explain what is constructor in Javascript class. It is a method that has to be included in a class when we define it, and it is a method where properties are assigned to a scope of the class. Constructors require a new keyword to work. It means constructor will be initialized if we will initialize the class as we did in the example above. Also, only one constructor can be used per class. If you don’t add a constructor inside your class, Javascript will do this for you with empty one: constructor() {}
3. Defining methods
Inside a class, we can define methods different than the constructor. Let’s see how it looks in the code:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
introduceYourself() {
return "Hello, my name is " + this.name;
}
}
var person = new Person("Mark", 30);
person.introduceYourself(); // returns 'Hello, my name is Mark'
In the example above, I’ve created a new method in Person class, called introduceYourself. This method takes this.name and returns the string. As you can see, creating a method is similar to creating a function, but without using a function keyword. In the code example, you can see how the method is called.
There is also a possibility to create static methods in the class. The difference is that static methods can be accessed only from the class, not from the object created by the class. Let’s check the code example to find out how to define a static method:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
static howAreYou() {
return "I am okay, and you?";
}
}
Person.howAreYou(); // returns 'I am okay, and you?';
var person = new Person("Mark", 30);
person.howAreYou(); // returns an error
To let the class know that the method we define should be static, we have to add a static keyword at the beginning of the method definition. Then, you can see it will return an error if you try to call it to form the object and if you access it from class directly then it’s okay, and the result will be as expected.
4. Extending classes and super keyword
Sometimes it happens that we want to „copy” the class and add some new methods or parameters to it. In this case, extending the class comes very handy. We can access all the features of the parent class and also add some new ones. To create a subclass form a parent class we use extend keywords. Let’s take a look at how it works in the example:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
yourAge() {
return "I am " + this.age;
}
}
class Kid extends Person {
howOldAreYou() {
return super.yourAge() + ". I am a child";
}
isAdult() {
if (this.age >= 18) {
return true;
} else {
return false;
}
}
}
var child = new Kid("Mary", 12);
child.howOldAreYou(); // returns 'I am 12. I am a child';
child.isAdult(); // returns false;
In the code above we extended a Person class to Kid class and used yourAge() method inside Kid class howOldAreYou(), and this was used with a super keyword which enabled parent methods usage in child class. Also property this.age is used to check condition in isAdult() functions.
5. Getters and setters
Like in objects in the class, we may also use getters and setters. Getter is created using get keyword, and setter is created by using a set keyword in the beginning. It’s a great idea to use getters and setters when we want to check or modify the value before it will be assigned to the object. Let’s check the code to find out how it works:
class Person {
constructor(name) {
// setter is called
this._name = name;
}
get name() {
return this._name;
}
set name(value) {
this._name = value;
}
}
var newPerson = new Person("Mary");
newPerson.name; // returns 'Mary'
newPerson.name = "Peter";
newPerson.name; // returns 'Peter'
In the example above, we can see getter and setter for the name property. In the constructor, when this._name is invoked, the setter is called to set the name. Getter and setter cannot have the same name as the property they set or get. Also if you want to use the setter to set a new property value, use it without parenthesis just like the property.
Conclusion
Classes feature in Javascript is relatively new, but the functionality of classes was there all the time, as prototype inheritance model and constructor functions. Now the syntax is way more friendly and more comfortable to create a clean, readable code. In this article, I went through the most important information about Javascript class, starting from defining a class, through constructor and methods, extending classes and finishing on using getters and setters. I hope knowledge from this article will clarify the usage of class in Javascript and help you to implement your code using class syntax. I think the implementation of classes came very handy for developers, but the same functionality could be achieved without it.
Thank you for reading, Anna from Duomly