javascript - 从类构造函数中的另一个属性引用属性的值

标签 javascript class javascript-objects

我试图从另一个属性中的另一个方法引用属性中先前方法返回的值
在构造函数中,但我收到“TypeError:无法读取未定义的属性'名称'”

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)

最佳答案

如果您希望此金额是动态的(您更新他们相应更新的值),它们需要是函数。我在下面为它们定义了函数。这意味着如果您更改其中一个计算变量,它们将自动更新。

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());

关于javascript - 从类构造函数中的另一个属性引用属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55950480/

相关文章:

CSS 合并两个类

c++ - 双指针对象数组 - 克隆元素

c++ - 使 C++ 类继承自 C 结构,推荐吗?

javascript - 将 [op.and] 添加到 Sequelize 查询对象

javascript - 使用点表示法访问对象的数字属性

javascript - 如何启用横向折叠

javascript - jQuery - 获取元素类型

javascript - 打字游戏——希望输入的所有字母都是小写

javascript - Javascript 中的错误 - 打开 URL 加上用户使用 Javascript 输入的文本

javascript - 带点击灰色背景的模态对话框