Classes are used in many object-oriented programming languages as a way to code efficiently and to bring modularity to the code. Classes are introduced in JavaScript as a part of ES6.
To declare a class in JavaScript, you can use one of the following methods:
A constructor is the first function of a class that is executed and it is called automatically. A constructor is used to create an object of the class upon
It is a function that uses the exact name constructor
. constructor
is generally an empty function, but it can also be created with parameters and some statements. Unlike other programming languages, there can only be one constructor in JavaScript.
In this method, the name of the class is preceded by the keyword class
, and the methods and attributes of the class are contained in curly braces ({}
).
class Square {
constructor {
this.side = 5;
}
};
The code above declares a class named Square
with a side length of 5
set as the attribute side
.
To declare a class with an expression, you can use a named expression or an unnamed one.
//unnamed expression
let Shape = class {
constructor(side_len) {
this.side = side_len;
}
};
//named expression
let Shape = class Square {
constructor(side_len) {
this.side = side_len;
}
};
The two methods above show different ways to declare the same class.
In either case, the class can be referenced with the name Shape
to which the class has been assigned.
A class can have many or few methods, which are basically functions that can use the attributes of a class.
An example of a method with the class Square
is provided below.
class Square {
constructor(side_len) {
this.side = side_len;
}
// Method
calculatePerimeter() {
return side*4;
}
};
An object is an instance of a class. It is an application of the blueprint that it provides.
const square1 = new Square(10);
The code above shows the syntax to declare an object of a class in JavaScript. Each object has a name, and if the constructor of the class has any parameters, they are passed as arguments to the class at the time of instantiation. In this case, 10
is provided as side_len
, which will be set as the attribute side
for the Square
class.
Code for classes is automatically executed in
strict
mode, which is semantically different than normal JavaScript in certain ways to make it more secure.
Below is an example of how classes are used in JavaScript.
class Cube { constructor(side_len){ // constructor this.side = side_len; } calculateVolume(){ // method return (this.side * this.side * this.side); } calculateSurfaceArea(){ // method return (6 * this.side * this.side); } }; const cube1 = new Cube(3); // object instantiation console.log("the surface area of the cube is: ", cube1.calculateSurfaceArea());
RELATED TAGS
CONTRIBUTOR
View all Courses