JavaScript ES5 does not have a built-in class type like Java or C#. However, functions can be used as classes to create objects and implement object-oriented programming concepts.
Note:
Functions can act as classes, and objects created using the new keyword are called instances.
What is a JavaScript Class?
A function can be used like a class in JavaScript. Properties are defined using the this keyword and objects are created using the new keyword.
Creating a Class using Function
Example:
function Person(){
this.firstName="unknown";
this.lastName="unknown";
}
var person1=new Person();
person1.firstName="Sohan";
person1.lastName="Kumar";
The function behaves like a class and person1 becomes its object.
Creating Multiple Objects
Each object stores its own values independently.
var person1=new Person();
person1.firstName="Sohan";
var person2=new Person();
person2.firstName="Kitu";
person1 and person2 have separate property values.
Using this Keyword
The this keyword binds properties to the current object.
function Person(){
this.firstName="Aman";
this.lastName="Kumar";
}
Adding Methods to Class
Methods can be added using function expressions.
function Person(){
this.firstName="unknown";
this.lastName="unknown";