

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Another method other than a constructor in a JavaScript class?
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.
<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
- Related Questions & Answers
- What is a constructor method in JavaScript?
- Add a method to a JavaScript object constructor?
- How to add a property, method to a JavaScript constructor?
- How to call the constructor of a parent class in JavaScript?
- Accessing variables in a constructor function using a prototype method with JavaScript?
- Accessing a Java class in other package.
- Does main() method accept arguments other than string array, in java?
- What is a default constructor in JavaScript?
- Returning values from a constructor in JavaScript?
- Add a property to a JavaScript object constructor?
- How can we call one constructor from another in the same class in C#?
- Class with a constructor to initialize instance variables in Java
- Why an interface doesn't have a constructor whereas an abstract class have a constructor in Java?
- How to convert a class to another class type in C++?
- Reference to a constructor using method references in Java8
Advertisements