javascript - 在包装函数中添加日志

标签 javascript recursion

我创建了一个函数包装器来帮助我提供各种打印语句:

function fnWrapper(fn, verbosity=false) {
    return function(...rest) {
        if (verbosity) console.log(`Calling "${fn.name}(${rest})"`)
        const res = fn(...rest); // possible to add debugging **within** this wrapped function?
        if (verbosity) console.log('==>', res)
        return res;
    }
}
function add(x,y) {
     return x===0 ? y : add(x-1, y+1);
}
const add2 = fnWrapper(add, true);

add2(2,3);
// Calling "add(2,3)"
// ==> 5

是否可以在函数本身中添加调试,例如,最基本的翻译如下函数:

function something(x,y) {
    console.log(arguments); // add this in
    ...
}

因此,对于上述函数,它会使 add 变为:

function add(x,y) {
    console.log(arguments);
    return x===0 ? y : add(x-1, y+1);
}

如果是这样,怎么办?

最佳答案

不,这是不可能的,您无法更改函数的功能。

问题是 add 调用 add,而 add2 也仅调用 add。不过,您可以简单地替换添加:

function fnWrapper(fn, verbosity=false) {
    return function(...rest) {
        if (verbosity) console.log(`Calling "${fn.name}(${rest})"`)
        const res = fn.call(this, ...rest);
        if (verbosity) console.log('==>', res)
        return res;
    }
}
function add(x,y) {
     return x===0 ? y : add(x-1, y+1);
}
add = fnWrapper(add, true); /*
^^^ */

add(2,3);

关于javascript - 在包装函数中添加日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72233666/

相关文章:

python - while循环更改变量[python]中的递归函数

java - 使用重复平方计算幂的递归方法

javascript - 替换 HTC 文件

javascript - Angular 4 : using component variables inside custom validator functions

javascript - 为什么这个立即调用的方法会返回窗口对象?

python - 递归遍历每个字符组合

java - 使用递归反转字符串

c - 如何在递归算法中将结果添加到数组中?

javascript - 选择单选按钮时隐藏/显示 div

javascript - 从 TWebBrowser 中的 GoogleMaps 获取纬度经度