Javascript Object Methods

Constructor Method

This method is a special type of method which is used to initialize and create an object. It is called when memory is allocated for an object.

Following points need to remember while using this constructor method:-

  • The constructor keyword is used to declare a constructor method.
  • The class can contain one constructor method only.
  • Use parent class constructor through super keyword.
Input:- 
    <script>
       class Employee {  
            constructor() {  
                this.id = 101;  
                this.name = "Mike Blaustein";  
            }   
        }  
        var emp = new Employee();  
        document.write(emp.id + " " + emp.name);		   </script>  

Output:-


Static Method

This method belong to the class instead of an instance of that class. So, an instance is not required to call the static method. These methods are called directly on the class itself.

Following points need to remember while using this static method:-

  • The static keyword is used to declare a static method.
  • The static method can be used to create utility functions.
  • The static method can be of any name.
  • A class can contain more than one static method.
  • If we declare more than one static method with a similar name, the JavaScript always invokes the last one.
  • We cannot use this keyword directly to call a static method within the non-static method. In such case, we can call the static method either using the class name or as the property of the constructor.
Input:- 
    <script>
       class Dashboard {  
            static user1() {  
                return "static method is invoked first time"  
            }  
            static user2() {  
                return "static method is invoked again"  
            }  
        }         
        document.writeln(Dashboard.user1()+"<br>");  
        document.writeln(Dashboard.user2());		    
   </script>  

Output:-