What is a class in JavaScript?



class

A class is a type of function, but instead of using the keyword 'function', keyword 'class' is used to initiate it, and the properties are assigned inside a constructor() method. The constructor() method is called each time the class object is initialized.

Example-1

In the following example, a class called 'company' is created and inside a constructor() method the name of the company is assigned and displayed the result in the output.

Live Demo

<html>
<body>
<p id="class"></p>
<script>
   class Company {
      constructor(branch) {
         this.name = branch;
      }
   }
   myComp = new Company("Tutorialspoint");
   document.getElementById("class").innerHTML = myComp.name;
</script>
</body>
</html>

Output

Tutorialspoint


Example-2

Live Demo

<html>
<body>
<script>
   class Company {
      constructor(branch) {
         this.name = branch;
      }
   }
   myComp = new Company("Rk enterprises");
   document.write(myComp.name);
</script>
</body>
</html>

Output

Rk enterprises

Advertisements