我试图从另一个属性中的另一个方法引用属性中先前方法返回的值
在构造函数中,但我收到“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/