在下面的测试代码中,工厂函数创建一个对象。新对象内部有 2 个方法: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());
最佳答案
最简单的方法是使用 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/