gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 20:54:35 26 4
gpt4 key购买 nike

在下面的测试代码中,工厂函数创建了一个对象。新对象内部有 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/

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