我有两个复制逻辑的函数,我想重构我的代码。作为类型传递的值是“day”或“night”。功能是:
function doBooking(type, rate, nights) {
if (type=="day") {
reservation.day(rate, nights, function(err, data) {
do (a)
do (b)
do (c)
});
} else {
reservation.night(rate, nights, function(err, data) {
do (a)
do (b)
do (c)
});
}
});
我想要聪明一点,并将其改进为类似以下内容,但它只是不起作用......
function doBooking(type, rate, nights) {
["reservation."+type](rate, nights, function(err, data) {
do (a)
do (b)
do (c)
});
});
答案 0 :(得分:0)
尝试这样的事情:
function doBooking(type, rate, nights) {
var _type = (type === "day") ? "day" : "night";
reservation[_type](rate, nights, function(err, data) {
do (a)
do (b)
do (c)
});
});
答案 1 :(得分:0)
如果他们共享相同的业务逻辑,为什么甚至打扰日/夜的单独功能呢?你不能只为一天中的时间添加另一个参数吗?
function doBooking(type, rate, nights) {
reservation.make(type, rate, nights, function(err, data) {
// (a), (b), & (c) happen inside the reservation handler
// If you do anything unique to day or night, do it here in the callback of the generic handler
});
}
除此之外,你可以在这里打破这些功能。从定义的类开始处理预留,因此您可以处理已知类型:
function Reservation (type, customer) {
this.type = type
this.customer = customer
this.rate
this.nights = []
this.isBooked
this.make = function(callback) {
longRunningBookingOperation(this, function(err, data) {
this.isBooked = data.result === "success" && !err
callback(err, data)
})
}
}
然后使用它:
const customer = Customer({firstname: "Tom", lastname: "Jones", id: 2392015572-1827})
var reservation = Reservation(ReservationTypeDay, customer)
reservation.make(err, data) {
// handle the result
})