What is class in Javascript
How to write class
What is Constructor
- Constructor is called automatically when class object is created
- Its name must be "constructor"
- Inside constructor, object properties are initialized
- Javascript add a default constructor, if you do not write your own constructor
Class Method
Class method is same as object method. You can write a class method to get parameters, to access object properties and return something.
In below example, we will write a class Student. Its constructor will initialize two properties, first name and second name.
Now we will write a class method that will return full name of student as
Output: John Wick
Class Inheritance
Keyword extends is used to inherit one class from another class. In this way, the class inherits all the methods of other class.
When multiple objects have some common properties than a separate class is created having common properties. All others inherits from that class.
In below example, We have a general class Person having a method getName() that returns property name
Now class Student inherits from class Person using keyword extends. In Student constructor, its mandatory to call its parent class constructor using super(name). Student show method display name and roll no of student. You can see that name is get using parent class method getName().
Now create object of Student and call its method show() as
Output:
Roll No: 123
Now create another class Teacher that inherits from Person class. Write show method in Teacher class, get name by calling parent class method getName() and salary from Teacher class property.
Now create object of class Teacher and call its method show as
Output:
Salary: 1000$
Class Static Method
You can write static method in class using static keyword. Static method is called without creating object of class. Just call class method using class name directly as below.
Output: I am John
You can pass parameter to class static method as
Output: I am John
Post a Comment