Static methods in JavaScript classes?

JavascriptObject Oriented ProgrammingFront End Technology

Static methods

Using static methods, we can access only the elements in a class but not the elements in the object. It is possible to call a static method only inside a class but not in an object. 

Example-1

In the following example, static() method is initiated in class "Company" rather than in an object "myComp". Therefore the contents in the static() method were executed in the output.

Live Demo

<html>
<body>
<p id="method"></p>
<script>
   class Company {
      constructor(branch) {
         this.name = branch;
      }
      static comp() {
         return "Tutorix is the best e-learning platform"
      }
   }
   myComp = new Company("Tesla");
   document.getElementById("method").innerHTML = Company.comp();
</script>
</body>
</html>

Output

Tutorix is the best e-learning platform


Example-2

In the following example, instead of the class, the object is called therefore no output will be executed. If we open the browser console we can see an error stating that "myComp.comp()" is not a function.

<html>
<body>
<p id="method"></p>
<script>
   class Company {
      constructor(branch) {
         this.name = branch;
      }
      static comp() {
         return "Tutorix is the best e-learning platform"
      }
   }
   myComp = new Company("Tesla");
   document.getElementById("method").innerHTML = myComp.comp();
</script>
</body>
</html>
raja
Published on 02-Aug-2019 13:15:20
Advertisements