A JavaScript
class is a type of function. Classes are declared with the class keyword, and
always add a constructor method and this constructor method is called each time
when the class object is initialized
Defining a Class:
We use
keyword Class to create a class.
Here is an
example which demonstrates how to define the class “Person”
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
As we know,
the constructor method always be called, when the class Person will be initialized.
We will
create an instance of Person Class by using the new keyword, and can pass
values through constructor.
var _person = new Person("Henry", "Ford");
Here
is a complete example (HTML & JS)
<h2>JavaScript Class - Demo</h2>
<p id="personDiv"></p>
<script>
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
};
var _person = new Person("Henry", "Ford");
document.getElementById("personDiv").innerHTML = _person.firstName;
</script>
Defining a Method:
The constructor
of class is a default of method, it is used to initialize the class properties.
You can define own custom method.
Here is an
example which demonstrates how to define method name() in Person class to get person’s
full name
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
name() {
return this.firstName + ' ' + this.lastName;
}
};
Inheritance - Extending a Class:
We use keyword
extends to implement class inheritance and derived class inherits all properties
and method of base class.
We use
keyword super to call the constructor method of base class or parent class.
Here is an
example which demonstrates how to inherit Person Class and create an Employee
Class.
class Employee extends Person
{
constructor(firstName, lastName, employeeID,
department) {
super(firstName, lastName);
this.employeeID = employeeID;
this.department = department;
}
};
Here
is a complete example (HTML & JS)
<h2>JavaScript Class - Demo</h2>
<p id="personDiv"></p>
<p id="personDepartment"></p>
<p id="personEmpID"></p>
<script>
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
name() {
return this.firstName + ' ' + this.lastName;
}
};
class Employee extends Person
{
constructor(firstName, lastName, employeeID,
department) {
super(firstName, lastName);
this.employeeID = employeeID;
this.department = department;
}
};
_person = new Employee("Henry", "Ford", 100, "IT");
document.getElementById("personDiv").innerHTML =
_person.name();
document.getElementById("personDepartment").innerHTML =
_person.department;
document.getElementById("personEmpID").innerHTML =
_person.employeeID;
</script>
No comments:
Post a Comment