gpt4 book ai didi

javascript - 对 'this' 的内部引用未在返回对象中解析

转载 作者:行者123 更新时间:2023-12-03 09:25:39 25 4
gpt4 key购买 nike

我正在尝试构造一个返回对象。为了避免逻辑重复,某些要素取决于其他要素。当我尝试使用“这个”时。引用已创建的项目,它无法解析。

function calcNextYear(lastYear) {
return {
age : lastYear.age + 1,
earnings : calcEarnings(lastYear.earnings,this.age),
savings : calcSavings(lastYear.endingAmount),
investmentIncome : calcInvestmentIncome(lastYear.endingAmount,this.age),
spending : calcSpending(this.age),
net : this.savings + this.investmentIncome - this.spending,
endingAmount : start.savingsAmount + this.net
}
}

未呈现的项目为 Netty 和期末金额。 “start”是一个现有对象。

最佳答案

这不是this的工作方式;您不能引用对象字面量中的先前值。你最好使用变量:

function calcNextYear(lastYear) {
var age = lastYear.age + 1;
var savings = calcSavings(lastYear.endingAmount);
var spending = calcSpending(age);
var investmentIncome = calcInvestmentIncome(lastYear.endingAmount, age);
var net = savings + investmentIncome - spending;
return {
age : age,
earnings : calcEarnings(lastYear.earnings, age),
savings : savings,
investmentIncome : investmentIncome,
spending : spending,
net : net,
endingAmount : start.savingsAmount + net
}
}

关于javascript - 对 'this' 的内部引用未在返回对象中解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31686778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com