How to define Classes in JavaScriptFirst important thing is that there are no classes in JavaScript. Functions can be used to simulate classes. In JavaScript, everything is an object and for inheritance, objects inherit from objects.
1. Using a function
This is the most common ways. We define a normal JavaScript function and then create an object by using the new keyword. We can use ‘this’ keyword to define properties and methods for an object.
For example:
function Car(brand) {
this.brand = brand;
this.color = "red";
this.showInfo = showCarInfo;
}
function showCarInfo() {
return this.brand + ' ' + this.color;
}
Now to use it, we can create an object of Car and call showCarInfo function. Like below:
var car = new Car('Audi');
alert(car.showInfo());
We can also sets its property like below:
car.color = ‘black’;
alert(car.showCarInfo());
Define methods internally
In above example, we see that the method showInfo() of the Car class was defined in a separate function showCarInfo(). This works fine but it has one disadvantage – we may end up defining a lot of functions and all are in the global namespace. This means we may have naming conflicts if we decide to create another function with the same name.
To avoid this problem, we can define our methods within the constructor function, like this:
function Car(brand) {
this.brand = brand;
this.color = "red";
this.showInfo = function() {
return this.brand + ' ' + this.color;
};
}
Using this syntax changes nothing in the way we instantiate the object and use its properties and methods.
2. Using literals
Literals are shorter way to define objects in JavaScript. To create an empty object we can do this way:
var obj = {};
So we can skip the class-like stuff and create an instance immediately. Here's the same functionality as described in the previous examples, but using object literal syntax this time:
var car = {
brand: "Audi",
color: "red",
showInfo: function () {
return this.brand + ' ' + this.color;
}
}
In this case we don't need to create an instance of the class, it already exists. So we simply start using this instance.
car.color = "black";
alert(car.showInfo());
Happy programming!!!