在一个对象内部,一个方法可以使用另一个方法的返回值吗?

时间:2018-04-20 22:55:31

标签: javascript methods javascript-objects

在下面的测试代码中,工厂函数创建一个对象。新对象内部有两种方法totalCost& withShipping。是否有我可以使用的模式允许withShipping使用totalCost的返回值?如配置它会引发错误。非常感谢您的帮助!

"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());

1 个答案:

答案 0 :(得分:2)

最简单的方法是使用this来访问当前实例化:

"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());

由于您正在使用工厂函数模式,另一个可行的方法是定义totalCost函数以及returnTest之外的所有其他 ,然后调用它:

"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());