Example to Understand How to Create a Class in JavaScript

How to Create a Class in JavaScript

In this article, we will see about how to create a class in javascript. Languages like C, C++, or java, might be very confusing. You would be more used to class-based inheritance. The javascript class was introduced in 2015. However, the class syntax does not introduce a new object-oriented inheritance model. In JavaScript, classes are primarily syntactical sugar over the existing prototypal inheritance. Let’s learn how it works:

Example of creating class

class person{
   constructor(fName, lName){
      this.firstName = fName;
      this.lastName = lName;
   }
   
   sayMyname() {
      return this.firstName + " " + this.lastName
   }
}
   const classP1 = new person('Bruce' , 'Wayne')
   document.write(classP1.sayMyname())

Output:

how to create a class in javascript
Steps:

  1. In the above code, we have created a class namely “person”.
  2. Then we created a constructor inside the class and it accepts two parameters fName and lName. Within the constructor, we assigned “this.firstName” to fName and “this.lastName” to lName.
  3. Create the method sayMyname() inside the class and returned the value firstname and last name.
  4. And then created instances of the class person by creating constant “classP1”. Then assigned the value ‘new’, it is used to allocate the memory and create an object for the class “person” with passing arguments.
  5. And finally, we print the ‘classP1.sayMyname()’.
  6. See the above output, the name “Bruce Wayne” is displayed successfully.

So, we can create instances and access the properties, and methods. The class keyword simply makes the syntax better. Let’s create the class inheritance by creating a child class for the class “person”.

Example of creating inheritance class

class SuperHero extends person{
      constructor(fName,lName){
         super(fName,lName)
         this.isSuperHero = true
      }
      fightCrime(){
         console.log('Fighting Crime')
      }
   }

   const batman = new SuperHero('Real' , 'Hero')
   document.write(batman.sayMyname())

how to create a class in javascript

Steps:

  1. Here, we have created another class called SuperHero and it extends the parent class person.
  2. Then we created a constructor inside the class SuperHero and it accepts parameters fName and lName.
  3. Inside the constructor, we invoke the “super()” method, which Javascript provides us and passes fName and lName. This will call the person class constructor. Once, we call the super method, we set the SuperHero properties and methods in the class.
  4. And then we defined the fightCrime() method and within that, we logged “Fighting Crime”.
  5. Finally, we create a new instance of batman and then printed it.
  6. See the above code, the output is displayed.

Leave a Reply