Super & Extends

Super & Extends

  • super keyword is used to access and call functions on an object’s parent

  • The extends keyword is used in a Class to create a class which is a child of another class

  • super and extends are used together to create parent-child relationships between Classes


Example

class Rectangle {
  constructor(height, width) {
    this._name = 'Rectangle'
    this._height = height
    this._width = width
  }

  sayName() {
    console.log(`Hi, I am a ${this._name}`)
  }

  calculateArea() {
    return this._height * this._width
  }
}

// use "extends" keyword to create a "child" class
// of the Rectangle class
class Square extends Rectangle {
  constructor(length) {
    // Here, it calls the parent class's constructor with lengths
    // provided for the Rectangle's width and height
    super(length, length)

    // Note: In derived classes, super() must be called before you
    // can use 'this'. Leaving this out will cause a reference error.
    this._name = 'Square'
  }

  calculateSurfaceArea() {
    return this.calculateArea() * 6
  }
}

const myRectangle = new Rectangle(5, 7)
myRectangle.sayName()
const rectangleArea = myRectangle.calculateArea()
console.log(rectangleArea)

console.log('----')

const mySquare = new Square(7)
mySquare.sayName()
const squareArea = mySquare.calculateArea()
console.log(squareArea)

// call calculateSurfaceArea() method owned by
// the child class (Square)
const surfaceAreaOfSquare = mySquare.calculateSurfaceArea()
console.log(surfaceAreaOfSquare)

JS Bin on jsbin.com


Exercise

  • Below we’ve created two classes Employee & Manager

  • Unfortunately our implementation contains some duplication

  • Use your knowledge of inheritance and “super” and “extends” keywords to remove the duplicated logic

class Employee {
  constructor(firstName, lastName) {
    this._firstName = firstName
    this._lastName = lastName
  }

  getFullName() {
    return `${this._firstName} ${this._lastName}`
  }
}

class Manager {
  constructor(firstName, lastName) {
    this._firstName = firstName
    this._lastName = lastName
    this._managedEmployees = []
  }

  getFullName() {
    return `${this._firstName} ${this._lastName}`
  }

  addEmployee(employee) {
    this._managedEmployees.push(employee)
  }

  listEmployees(employees) {
    return this._managedEmployees.map(member => member)
  }
}

const employee1 = new Employee("Mickey", "Mouse")
const employee2 = new Employee("Donald", "Duck")
console.log(employee1.getFullName())
console.log(employee2.getFullName())


const manager = new Manager("Minnie", "Mouse")
console.log(manager.getFullName())
manager.addEmployee(employee1)
manager.addEmployee(employee2)

const minniesTeam = manager.listEmployees()
console.log(minniesTeam)

JS Bin on jsbin.com