在下面的测试代码中,工厂函数创建一个对象。新对象内部有两种方法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());
答案 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());