Search code examples
javascriptclassjavascript-objects

Referencing the value of a property from another property in a Class' constructor


I am trying to reference the value returned in a previous method in a property from another method in another property
within the constructor but I get a "TypeError: Cannot read property 'name' of undefined"

class Loans {
  constructor(user, loanAmount, tenor, id = 0, status = 'pending', repaid = 'false') {
    this.id = id + 1;
    this.user = user;
    this.loanAmount = loanAmount;
    this.tenor = tenor;
    this.status = status;
    this.repaid = repaid;
    this.interest = (function interest() {
      return (loanAmount * 0.05);
    }());
    this.monthlyInstall = (function monthlyInstall() {
      return (loanAmount + this.interest) / tenor;
    }());
    this.balance = (function balance() {
      return (loanAmount + interest);
    }());
    this.createdAt = new Date().toLocaleString();
  };

};
const loan = new Loans('steve.jobs', 50000, 5);
console.log(loan);

but I got an error ->

      return (loanAmount + this.interest) / tenor;
                                ^

TypeError: Cannot read property 'interest' of undefined
    at monthlyInstall (C:\Users\DEBAYO\Desktop\JavaScript\Challenges\testing.js:183:33)
    at new Loans (C:\Users\DEBAYO\Desktop\JavaScript\Challenges\testing.js:184:6)

Solution

  • If you want this amount to be dynamic (you update a value they update accordingly) they need to be functions. I made them defined functions below. This means that if you change one of the calculating variables they will be updated automatically.

    class Loans {
      constructor(user, loanAmount, tenor, id = 0, status = 'pending', repaid = 'false') {
        this.id = id + 1;
        this.user = user;
        this.loanAmount = loanAmount;
        this.tenor = tenor;
        this.status = status;
        this.repaid = repaid;
        this.createdAt = new Date().toLocaleString();
      };
      
      interest = () => (this.loanAmount * 0.05);
      monthlyInstall = () => (this.loanAmount + this.interest()) / this.tenor;
      balance = () => (this.loanAmount + this.interest());
    };
    const loan = new Loans('steve.jobs', 50000, 5);
    console.log(loan);
    console.log(loan.interest());
    console.log(loan.monthlyInstall());
    console.log(loan.balance());
    loan.tenor = 6;
    console.log(loan);
    console.log(loan.interest());
    console.log(loan.monthlyInstall());
    console.log(loan.balance());