Javascript Classes

Class contains various class members within a body including methods or constructor. The class is executed in strict mode. So, the code containing the silent error or mistake throws an error.

The class syntax contains two components:-

  • Class declarations
  • Class expressions

Class Declaration

A class in Javascript is defined by using a class declaration. A class keyword is used to declare a class with any particular name. According to JavaScript naming conventions, the name of the class always starts with an uppercase letter.

Input:-
 <script>  
	   class Employee{   
        constructor(id,name){  
            this.id = id;  
            this.name = name;  
        }    
        detail(){  
            document.write(this.id+" "+this.name+"<br>")  
       	}  
    }   
    var e1=new Employee(1000,"Mike Graynor");  
    var e2=new Employee(1001,"Zola Martin");   
    e1.detail();   
    e2.detail(); 
</script>

Output:-


Class Expression

A class expression doesn’t require an identifier after the class keyword. And we can use a class expression in a variable declaration and pass it into a function as an argument. For example, the following defines a class expression:-

Input:-
 <script>  
	   var emp = class{   
       constructor(id,name){  
           this.id = id;  
           this.name = name;  
       }  
       detail() {  
           document.write(this.id+" "+this.name+"<br>")  
       }  
     }   
     var e1 = new emp(1000,"Mike Graynor");  
     var e2 = new emp(1001,"Zola Martin");  
     e1.detail(); 
     e2.detail();  
</script>

Output:-