Inheritance

We mentioned that class members marked with the protected access modifier are also visible to any classes that are inherited from the class that they're declared in, and so we'd better discuss inheritance real quick.

Inheritance does not mean that the classes that we create will become independently wealthy; that's a whole different kind of inheritance. The kind of inheritance that we're talking about is a little less exciting, but far more useful for our JavaScript code.

A class can inherit from another class. In order for a class to do that, we use the extends keyword in the class definition. Let's switch gears once more, this time going from Animal to Employee (though I've seen some bathrooms and kitchens at a couple of my client locations, and I can tell you that some employees can also be animals). Let's get to the code:

class Employee {
constructor(name) {
this.name = name;
this.title = "an employee";
}
annouceThyself() {
return `Hi. My name is ${this.name} and I am ${this.title}.`;
}
}
class Manager extends Employee {
constructor(name) {
super(name);
this.title = "a manager";
}
}

Let's create an Employee object, and have the employee announce himself:

var emp = new Employee("Goofy");
console.log(emp.annouceThyself());
// Hi. My name is Goofy and I am an employee.

Let's create a Manager object and have the manager announce himself:

var mgr = new Manager("Mickey");
console.log(mgr.annouceThyself());
// Hi. My name is Mickey and I am a manager.

Here's what's going on:

  1. We created an Employee class.
  2. We created a Manager class that inherits from Employee.
  3. The Manager class does not have any properties or functions, other than it's constructor. However, it inherits the properties (name and title), and the method (annouceThyself), from the Employee class.
  4. The constructor in the Manager class calls the constructor in the Employee class, passing in the manager's name.
  5. The manager's constructor reassigns the value for the title property.

This was fairly straightforward but there are two takeaways here for you to remember:

  • The inheriting class gets all the class members from the class that it inherits from
  • One constructor can call it's parent's constructor, and this can continue up the chain, if the parent had a parent, and so on
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.200.105