In programming, courses are the blueprints for objects.
Letβs create a category named Individual.
class Individual {
//js object constructor.
constructor() {
this.identify = "Max";
}
printMyName() {
console.log(this.identify);
}
}
Above class Individual is having two issues in it is physique, a constructor operate to create and initialise occasion variable and a way βprintMyNameβ to print the worth in occasion variable.
The above class βIndividualβ is a blueprint. With a view to give life to this class, weβve to create object for this class βIndividualβ.
Letβs create an object for the category βIndividualβ.
const individual = new Individual();
individual.printMyName();
Within the above code, weβre creating an object utilizing new key phrase.
And weβre calling the tactic βprintMyNameβ to print the worth in occasion variable.
Inheritance
Like a toddler inherits the behaviour of his/her dad and mom, we will additionally make a category inherits the strategies and properties of one other class.
Letβs create a inherited class,
class Human {
constructor(){
this.gender="male";
}
printGender() {
console.log(this.gender);
}
}
class Individual extends Human {
//js object constructor.
constructor() {
tremendous();
this.identify = "Max";
}
printMyName() {
console.log(this.identify);
}
}
Right here we use the key phrase extends to make the category βIndividualβ inherits the strategies and attributes of the category βHumanβ.
Additionally we use tremendous() inside constructor operate as a result of, weβre overriding the constructor operate at school βIndividualβ and due to that the constructor operate at school βHumanβ will not have any impact. The tremendous() operate is used to present entry to strategies and properties of a mum or dad or sibling class.
Now letβs create object from this inherited class,
const individual = new Individual();
individual.printGender();
Since weβre inheriting the category βHumanβ at school βIndividualβ, we will entry the tactic printGender() of βHumanβ class from the category βIndividualβ.