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

标签 javascript methods javascript-objects

在下面的测试代码中,工厂函数创建一个对象。新对象内部有 2 个方法:totalCostwithShipping。我可以使用一种模式来允许 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());

最佳答案

最简单的方法是使用 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());

关于javascript - 在对象内部,一个方法是否可以使用另一个方法的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49950678/

相关文章:

javascript - 将两个数组合并到多个对象

javascript - 重新加载 html5 视频标签的源在 chrome 上不起作用

javascript - react 或声明与功能

javascript - 自定义上下文菜单不适用于 HTML 视频标记

java - 方法(String str)和方法(Final String str)有什么区别

java - 如何让程序显示可被 5 整除的值的总和,而不是仅显示值本身?

javascript - Mootools:添加输入文本字段

ruby - ruby 中的类/静态方法有什么用?

javascript - 如何摆脱数字属性的自动排序?

javascript - 返回值作为对象属性