0

I am trying to construct an object for return. To avoid duplication of logic, some of the elements hinge on others. When I attempt to use 'this.' to reference already created items, it does not resolve.

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
    }
}

The items not rendering are net and ending amount. 'start' is an existing object.

Ivan
  • 1,487
  • 1
  • 16
  • 27
jgrif
  • 1
  • *this* is *window* in this code if you initialize it in global scope – Ivan Jul 28 '15 at 20:52
  • 1
    [How does the "this" keyword work](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Andreas Jul 28 '15 at 20:53
  • Chances are for `this` to work in the context jgrif is wanting, you'd have to bind it's context. Still don't think that's correct. – Orpheus Jul 28 '15 at 20:58

1 Answers1

1

That's not the way this works; you cannot refer to previous values in an object literal. You're better off using variables:

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
    }
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Jacob
  • 77,566
  • 24
  • 149
  • 228