我正在尝试从另一个属性中的另一个方法引用一个属性中先前方法中返回的值
构造函数中,但出现“ 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)
答案 0 :(得分:1)
如果您希望此金额是动态的(您更新一个值,它们就会相应地更新),则它们必须是函数。我在下面为它们定义了函数。这意味着,如果您更改其中一个计算变量,它们将自动更新。
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());
答案 1 :(得分:0)
代替
this.monthlyInstall = (function monthlyInstall() {
return (loanAmount + this.interest) / tenor;
}());
只要做
this.monthlyInstall = (loanAmount + this.interest) / tenor;
或者您需要将“ this”引用传递到您的monthlyInstall()方法中,因为否则它不知道“ this”是什么。