前后各功能执行后调用特定的功能

问题描述 投票:2回答:2

我需要在每次函数执行后调用特定的功能

例如,我有这些功能

function a() {
    // logic
}

function b() {
    // logic
}

function c() {
    // logic
}

我现在正在做的是

function a(){
    c();
    // logic
    c();
}

function b(){
    c();
    // logic
    c();
}

是有更好的办法在春天这样类似的建议

javascript function
2个回答
2
投票

你可以只定义这样的“高阶”辅助函数:

function wrapWith(baseFunc, otherFunc) {
    function wrapper() {
        otherFunc();
        baseFunc();
        otherFunc();
    }
    return wrapper;
}

然后,只需定义a = wrapWith(a, c)b = wrapWith(b, c),等等。(如果你有的时候会需要“展开” ab,只是分配包裹版本的新变量,而不是覆盖ab。)


0
投票

你可以尝试创建它接受这两个函数作为参数的包装功能和执行你想有一个顺序。

const wrapper = (logic, advice)=>{
advice();
let log  = logic()
advice()
return log
}

然后调用它

wrapper(a,c)
wrapper (b,c);
© www.soinside.com 2019 - 2024. All rights reserved.