Learn how to create classes in JavaScript

0


In 2015, the ES6 version of the JavaScript programming language was released. This release introduced major upgrades to the language and officially placed it in the category of object-oriented programming languages ​​among other languages ​​such as Java and C ++.

Object-oriented programming focuses on objects and the operations that can be performed on them. However, before you can have items, you must have a class.

JavaScript classes are one of the revolutionary features provided with the ES6 version of the language. A class can be described as a template used to create objects.

In this tutorial article, you will learn how to create and manipulate objects using JavaScript classes.

JavaScript class structure

When creating a class in JavaScript, you will always need one fundamental component: the to classify keyword. Almost all other aspects of the JavaScript class are not required for its successful execution.

A JavaScript class will run naturally if a constructor is not provided (the class will simply create an empty constructor at runtime). However, if a JavaScript class is created with constructors and other functions but no class keyword is used, that class will not be executable.

the to classify keyword (which should always be lowercase) is a necessity in the class structure of JavaScript. The following example is the general syntax of a JavaScript class. The syntax of the JavaScript class is below:

class ClassName{
//class body
}

Create a class in JavaScript

In programming, a class can be seen as a generalized entity used to create a specialized object. For example, in a school environment, a generalized entity (a class) can be students and a students object can be John Brown. But before you create an object, you need to know what data it will store and this is where JavaScript constructors come in.

Using constructors in JavaScript classes

A constructor is vital to the class creation process for several reasons; it initializes the state of an object (via its attributes) and it is called automatically when a new object is instantiated (defined and created).

Use an example constructor

Below you’ll see an example constructor with an explanation of what it means.

class Student{
constructor(firstName, lastName, startDate){
this.firstName = firstName;
this.lastName = lastName;
this.startDate = startDate;
}
}

The above code shows an important aspect of the JavaScript class constructor; unlike other languages ​​such as Java and C ++, a JavaScript constructor does not use the class name to create a constructor. He uses the builder as you can see in the example above.

Related: Learn How to Create Classes in Java

the builder in the example above takes three parameters and uses the this keyword to assign parameters to the current instance of the class. It might sound a little confusing, but what you need to understand is that a class can be thought of as a template used to create many houses.

Each house built can then be considered as an object of this class. Although each of these houses is created with the same plan, they are distinguished by their specific geographic location or who owns them.

the this The keyword is used to distinguish each object created by a class. It ensures that the correct data is stored and processed for every object created using the same class.

Create an object in JavaScript

Constructors are important in a language like JavaScript because they mean the number of attributes that an object of a specific class should have. Some languages ​​require that an attribute (variable) be declared before it can be used in a constructor or any other method. However, this is not the case with JavaScript.

Related: How to Declare Variables in JavaScript

Looking at the student class constructor above, you can discern that an object of this class will have three attributes.

Creating a sample object

Below you will see an example of creating an object in JavaScript.

//create a new object
const john = new Student('John', 'Brown', '2018');

The above code uses the Student class to create an object.

When creating an object of a class, you must use the New keyword, followed by the name of the class and the values ​​you want to assign to the respective attributes. You now have a new student with the first name John, the last name Brown, and a start date of 2018. You also have a constant variable: John. This variable is important because it allows you to use the object that is created.

Without the John variable, you can always create a new object using the Student class, but then there will be no way to access that object and use it with the different methods of the class.

Using methods in JavaScript classes

A method is a function of a class used to perform operations on objects created from the class. A good method to add to the class of students is one that generates a report on each student.

Example of creating class methods

Below is an example of creating class methods in JavaScript.

class Student{
constructor(firstName, lastName, startDate){
this.firstName = firstName;
this.lastName = lastName;
this.startDate = startDate;
}
// report method
report(){
return `${this.firstName} ${this.lastName} started attending this institution in ${this.startDate}`
}
}

The above class contains a method that will generate a report on each student created with the Student to classify. To use the report() you will need to use an existing object of the class to make a simple function call.

Using the “create an object” example above, you should have an object from the Student class assigned to the variable John. Using Johnyou can now successfully call the report() method.

Example of using class methods

Below is an example of using class methods in JavaScript.

//create a new object
const john = new Student('John', 'Brown', '2018');
//calling the report method and storing its result in a variable
let result = john.report();
//printing the result to the console
console.log(result);

The above code uses the Students class to produce the following output to the console:

John Brown started attending this institution in 2018

Using static methods in JavaScript classes

Static methods are unique because they are the only methods in a JavaScript class that can be used without an object.

In the example above, you cannot use the report() method without object of the class. It is because the report() The method relies on the attributes of an object to produce a desirable result. However, to use a static method, you will only need the name of the class that stores the method.

Creating an example static method

Below is an example of a static method for JavaScript.

class Student{
constructor(firstName, lastName, startDate){
this.firstName = firstName;
this.lastName = lastName;
this.startDate = startDate;
}
// report method
report(){
return `${this.firstName} ${this.lastName} started attending this institution in ${this.startDate}`
}
//static method
static endDate(startDate){
return startDate + 4;
}
}

The important thing to note from the example above is that each static method begins with the static keyword.

Using an example static method

Below is an example of using a static method in JavaScript.

//calling a static method and printing its result to the console
console.log(Student.endDate(2018));

The line of code above uses the Students class to produce the following output to the console:

2022

Creating a JavaScript class is easy

There are several things you should remember if you want to create a JavaScript class and instantiate one or more objects from it:

  • A JavaScript class must have the to classify keyword.

  • A JavaScript constructor indicates the number of values ​​an object can have.

  • General class methods cannot be used without an object.

  • Static methods can be used without object.

the console.Newspaper() is used throughout this article to provide the results of using general and static methods in a JavaScript class. This method is a useful tool for any JavaScript developer because it makes the debugging process easier.

Familiarize yourself with the console.log () is one of the most important things you can do as a JavaScript developer.


Code displayed on a laptop screen

The ultimate JavaScript cheat sheet

Get a quick refresher on JavaScript elements with this cheat sheet.

Read more


About the Author


Share.

Leave A Reply