GUIDE: OOP Inheritance In Javascript

❯❯ Implementing Inheritance Using Constructor Function

If we want to use inheritance in a constructor function we need to utilize the .call() method from the Function.prototype object.

Implementing inheritance using .call()
click to copy code segment
/* Create the constructor function from which to inherit */
const BankAccount = function (balance) {
  this.balance = balance;
};

/* Create an inheriting constructor function */
const SavingsAccount = function (balance, initDeposit, percent) {
  /* use constructor of BankAccount with this pointing to savingsAccount */
  BankAccount.call(this, balance);
  this.initDeposit = initDeposit;
  this.percent = percent;
};
/* Create prototype linkage (using prototypal chaining)  */
SavingsAccount.prototype = Object.create(BankAccount.prototype);

                              

❯❯ Implementing Inheritance Using Classes

If we use the class syntax we need to use the 'extends' keyword and the super() constructor inside the inheriting class constructor.

implement inheritance with class syntax
click to copy code segment
class BankAccount = {
  constructor(balance) {
    this.balance = balance;
  }
};

class SavingsAccount extends BankAccount = {
  constructor(balance, initDeposit, percent) {
    super(balance);
    this.initDeposit = initDeposit;
    this.percent = percent;
  }
};

                              

profile picture

WHO AM I?

Teacher
Thinker
Tinkerer