JavaScript Classes
A JavaScript Class is blueprint or template that is used create objects o this class type.
For example, Set, Map, etc., are classes in JavaScript, that are used to create set objects, map objects, etc.
In addition to the builtin classes in JavaScript, or the classes that come with libraries, we can also define our own classes and create objects of these user-defined class types. In this tutorial, we will learn the syntax of a class, and write some classes.
Syntax
The syntax of a typical class in JavaScript is
class ClassName {
constructor() {
}
//methods
}
where ClassName is the name given to this class.
class | Keyword to define a class in JavaScript. |
ClassName | User-defined name to refer this class from other parts of program. |
constructor | Constructor method for this class, which is run when an object is created of this class type. |
We can initialize properties for a class object when creating an object of this class type. To initialize such properties, constructor() method is used.
Examples
The following is a class named Student whose constructor can take two values and initializes properties name
and roll_no
.
class Student {
constructor(name, roll_no) {
this.name = name;
this.roll_no = roll_no;
}
}
We can also define methods for this class. Let us define a method named getDetails
that takes no parameters, and returns a string containing details of this Student object.
class Student {
constructor(name, roll_no) {
this.name = name;
this.roll_no = roll_no;
}
getDetails() {
return 'Name: ' + this.name + '\nRoll: ' + this.roll_no;
}
}
Now, let us create an object of this class type Student
with initial values passed to constructor, and call the method getDetails()
on this object.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
class Student {
constructor(name, roll_no) {
this.name = name;
this.roll_no = roll_no;
}
getDetails() {
return 'Name: ' + this.name + '\nRoll: ' + this.roll_no;
}
}
var s1 = new Student('Arjun', 14);
var result = s1.getDetails();
document.getElementById("output").innerHTML = result;
</script>
</body>
</html>
We can define methods of a class that can take parameters. In the following example, we define a method for Student
class that takes a parameter and returns a string.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
class Student {
constructor(name, roll_no) {
this.name = name;
this.roll_no = roll_no;
}
getDetails() {
return 'Name: ' + this.name + '\nRoll: ' + this.roll_no;
}
assignHomeWork(homeWork) {
return this.name + ' is assigned with "' + homeWork + '".';
}
}
var s1 = new Student('Arjun', 14);
var result = s1.assignHomeWork('Essay on Elephant');
document.getElementById("output").innerHTML = result;
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned about Classes in JavaScript, and how to define then, and use them in our program, with examples.