Search code examples
javascriptmethodsjavascript-objects

Inside an object is it possible for a method to use the return value of another method?


In the test code below a factory function creates an object. Inside the new object are 2 methods, totalCost & withShipping. Is there a pattern I can use that will allow withShipping to use the return value of totalCost? As configured it throws an error. Thanks so much for any help!

"use strict"

function factoryTest(x) {
    let returnTest = {
        numberOfEngines: x.numberOfEngines,
        costPerEngine: x.costPerEngine,
        totalCost: function() {
            return x.numberOfEngines * x.costPerEngine;
        },
        withShipping: function() {
            return x.totalCost() * 2;
        }

    }
    return returnTest;
}

let aircraft = factoryTest({numberOfEngines: 2, costPerEngine: 40000});

console.log(aircraft.totalCost());
console.log(aircraft.withShipping());


Solution

  • The easiest method would be to use this to access the current instantiation:

    "use strict"
    
    function factoryTest(x) {
        let returnTest = {
            numberOfEngines: x.numberOfEngines,
            costPerEngine: x.costPerEngine,
            totalCost: function() {
                return x.numberOfEngines * x.costPerEngine;
            },
            withShipping: function() {
                return this.totalCost() * 2;
            }
    
        }
        return returnTest;
    }
    
    let aircraft = factoryTest({numberOfEngines: 2, costPerEngine: 40000});
    
    console.log(aircraft.totalCost());
    console.log(aircraft.withShipping());

    Another workable method, since you're using the factory function pattern, would be to define the totalCost function and everything else outside of returnTest and then call it:

    "use strict"
    
    function factoryTest({
      numberOfEngines,
      costPerEngine
    }) {
      const totalCost = () => numberOfEngines * costPerEngine;
      return {
        numberOfEngines,
        costPerEngine,
        totalCost,
        withShipping: () => totalCost() * 2,
      };
    }
    
    const aircraft = factoryTest({
      numberOfEngines: 2,
      costPerEngine: 40000
    });
    
    console.log(aircraft.totalCost());
    console.log(aircraft.withShipping());