Another method other than a constructor in a JavaScript class?

JavascriptObject Oriented ProgrammingFront End Technology

The constructor() method is special. It is where we initialize properties. It is called automatically when a class is initiated. In fact, if we do not have a constructor() method, JavaScript will add an invisible and empty constructor() method. We are also free to make our own methods. The creation of our own method follows the same syntax as the original syntax.

Example

In the following example, rather than using the default method constructor() the properties were actually initialized in a user given method called "anotherMet()". Through this method, the actual result is executed in the output as shown.

Live Demo

<html>
<body>
<p id="method"></p>
<script>
   class Company {
      constructor(branch) {
         this.name = branch;
      }
      anotherMet(x) {
         return x + " is the head of " + this.name;
      }
   }
   myComp = new Company("Tesla");
   document.getElementById("method").innerHTML = myComp.anotherMet("Elon musk");
</script>
</body>
</html>

Output

Elon musk is the head of Tesla
raja
Published on 02-Aug-2019 15:15:16
Advertisements