In javascript, a class is a blueprint or template, hold properties (data members) and methods, used to create objects at runtime. classes are introduced in javascript by ECMAScript 2015 (ES16).
Javascript class cannot be hoisted.
Data member, properties | Variables |
Methods | class functions |
JavaScript Class Syntax
class ClassName{
constructor() { ... }
method1() { ... }
method2() { ... }
}
In javascript, class can only have one constructor and any number of methods (one or more than one method).
Class constructor
Constructor is a method which automatically invokes, when object of class gets created. It is used to initialized class variables on object creation.
Syntax
class ClassName{
constructor() { ... }
}
constructor() is used to add constructor in a class, it accepts arguments.
Class Constructor and Parameters
class ClassName{
constructor(arg1,arg2,arg3) {
this.arg1 = arg1;
this.arg2 = arg2;
this.arg3 = arg3;
}
}
Here, this.arg1, this.arg2, this.arg3 is class properties, data member or class variable.
Creating a Class
- To create a class, class keyword is used then space and then Class name.
- Class body, consists of open curly brace {, and close curly brace }.
- Inside these curly braces, constructor, properties (data member) and methods are used.
<script>
class Phone{
//data members
constructor(arguments...) {
//data members
}
method1(){
// set of statements
}
method2(){
// set of statements
}
}
</script>
Creating class with properties or data member
<script>
class Phone{
color = "black";
constructor(company, make) {
this.company = company;
this.make = make;
this.year = 2024;
}
}
</script>
Below table provides details about, above class properties and its values.
Properties/Data Member | Value/ argument assigned |
---|---|
color | black |
this.company | company |
this.make | make |
this.year | 2024 |
Class Properties are variables which hold values, and allows to perform different operations.
Creating class with methods
In a class, method performs action on properties. In below example phoneDetails() method outputs Hello World.
<script>
class Phone{
phoneDetails(){
document.write("Hello World");
}
}
</script>
Creating class object
<script>
class Phone{
constructor(company) {
}
}
const p = new Phone("Samsung");
</script>
In javascript. new keyword is used to create a class object, and class name with parameters as per constructor should be passed. const, var or let can be used to hold class object.
Complete class example
<script>
class Phone{
color = "black";
constructor(company, is5G) {
this.company = company;
this.is5G = is5G;
this.year = 2024;
}
phoneDetails(){
document.write(this.company + " " + this.is5G + " " + this.color + " " + this.year);
}
}
const p = new Phone("Samsung","Yes");
p.phoneDetails();
</script>
Output: Samsung Yes black 2024