If we want to use inheritance in a constructor function we need to utilize the .call() method from the Function.prototype object.
/* 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);
If we use the class syntax we need to use the 'extends' keyword and the super() constructor inside the inheriting class constructor.
class BankAccount = {
constructor(balance) {
this.balance = balance;
}
};
class SavingsAccount extends BankAccount = {
constructor(balance, initDeposit, percent) {
super(balance);
this.initDeposit = initDeposit;
this.percent = percent;
}
};