In this article, we'll learn how to create classes in javascript. If we search web for "classes in javascript", we'll find a lot of articles explaining the prototypal nature of javascript and focussing on the fact that classes in javascript are more of a syntactical sugar. We'll not go much into that discussion here, we'll rather focus on how to use the concept by giving code examples.
class | A class is a blue print or a template for all the methods and variabes in any particular kind of object. |
---|---|
constructor | It is a special method in a class which usually has the same name as the class and is called when the object of the class is created. |
extends | It is used by the derived class to inherit the properties of the base class. |
this | It is used to refer to the owner of the function being executed rather than the object calling it. |
super | It is used by the derived class to call the functions of base class. |
To create a class in javascript we use the following syntax :
class CLASS_NAME {
constructor( params . . . ) {
Initializations . . .
}
class functions . . .
}
Here is the example of how constructor is defined and used in javaScript.
class Vehicle{
constructor( engine , wheels ){
this.engine = engine;
this.wheels = wheels;
}
printStats() {
console.log(this.engine);
console.log(this.wheels);
}
}
var Veh = new Vehicle("Petrol",4);
Veh.printStats();
You can run this code using the following command.
node class.js
Petrol
4
Note : We are using node.js to run our Javascript code.
Here is the example of how extends is defined and used in javaScript.
//Parent class
class Vehicle{
constructor( engine , wheels ){
this.engine = engine;
this.wheels = wheels;
}
getStats() {
console.log(this.engine);
console.log(this.wheels);
}
getEngine() {
return this.engine
}
setEngine(engine){
this.engine = engine
}
getWheels(){
return this.wheels
}
setWheels(wheels){
this.wheels = wheels
}
}
//Child class
class Car extends Vehicle {
constructor(engine,wheels,color,year,model){
super(engine, wheels)
this.color= color;
this.year= year;
this.model= model;
}
getStats() {
console.log(this.engine);
console.log(this.wheels);
console.log(this.color);
console.log(this.year);
console.log(this.model);
}
}
// Creating the object
var u = new Car("Petrol",4,"Red",2015,"tesla");
u.getStats();
You can run this code using the following command.
node class.js
Petrol
4
Red
2015
tesla