- Classes are the core feature of next generation JavaScript. Classes are generally blueprints of objects. A Class can have both properties and methods.
- Methods are functions attached to classes where properties acts as variables and are attached to classes.
- A Class is instantiated with a new keyword.
- Classes also support Inheritance. A class can inherit another class and use its properties and methods.
- Constructor is a default method used for creating and initializing an object created with the class. This is automatically executed whenever you instantiate a class. In this, you can set up properties with this keyword.
- Let’s see an example:
class Person{
constructor(){
// setting up properties using this keyword
this.name="Akanksha";
this.address="Delhi";
}
// creating a custom method within a class
getName(){
console.log("Name: " + this.name + " and Location: " + this.address);
}
}
// creating an object of the class using new keyword.
// constructor function is called as soon as you instantiate a class using new keyword
const prsn = new Person();
// calling method using the object of the class
prsn.getName();
You can also pass the data while instantiating the class
Related Article: Inheritance in JavaScript


2 thoughts on “Classes in JavaScript”