Classes are bits of code that encompass multiple objects, methods and allow manipulation for its member variables and functions. Within each language, a class has different syntax and the same holds true for Javascript.
In this language, a class is simply a variant of functions. Using the class functionality one can define the constructor and the prototype functions for the member objects in one encompassing block.
To create a class in Javascript, a few things should be noted:
class
as shown in the example below:class Student{// Elements within the class are declared and defined inside the brackets}
A class has a default constructor which is empty but can also be defined within the class method. Unlike in other languages, to declare the constructor, Javascript has a specific keyword called constructor
. The parameter(s) given to the constructor
are then used to define elements within the class; class members.
The example below shows how this is done:
class Student{//Declaring the constructorconstructor(name){this.name=name;}}
,
as shown in the example below:class Student{//This is the class constructorconstructor(name){this.name=name;}//There is no comma between the two methods//This is a method defined in the class; member methoddisplayStudentname(){console.log(this.name);}}
new
. To see how this is done, look at the code below:class Student{constructor(name){this.name=name;}displayStudentname(){console.log(this.name);}}//Creating an instance of a classlet studentOne = new Student("JohnDoe");studentOne.displayStudentname();
Note: All classes in Javascript use strict mode.