我需要在每次函数执行后调用特定的功能
例如,我有这些功能
function a() {
// logic
}
function b() {
// logic
}
function c() {
// logic
}
我现在正在做的是
function a(){
c();
// logic
c();
}
function b(){
c();
// logic
c();
}
是有更好的办法在春天这样类似的建议
你可以只定义这样的“高阶”辅助函数:
function wrapWith(baseFunc, otherFunc) {
function wrapper() {
otherFunc();
baseFunc();
otherFunc();
}
return wrapper;
}
然后,只需定义a = wrapWith(a, c)
,b = wrapWith(b, c)
,等等。(如果你有的时候会需要“展开” a
和b
,只是分配包裹版本的新变量,而不是覆盖a
和b
。)
你可以尝试创建它接受这两个函数作为参数的包装功能和执行你想有一个顺序。
const wrapper = (logic, advice)=>{
advice();
let log = logic()
advice()
return log
}
然后调用它
wrapper(a,c)
wrapper (b,c);