[英]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" 在构造函数中,但出现“ 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)
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());
instead of 代替
this.monthlyInstall = (function monthlyInstall() {
return (loanAmount + this.interest) / tenor;
}());
just do 做就是了
this.monthlyInstall = (loanAmount + this.interest) / tenor;
Or you need to pass "this" reference into your monthlyInstall() -method, because otherwise it does not know what "this" is. 否则您需要将“ this”引用传递到您的monthlyInstall()方法中,因为否则它不知道“ this”是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.