且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以在不修改原始代码的情况下向现有 javascript 函数添加一些代码?

更新时间:2023-09-20 18:34:16

你不能修改函数,但你可以包装它们并用包装器替换函数.

You can't modify functions, but you can wrap them and replace the function with the wrapper.

此类(参见现场演示):

function logFactory(func, message) {
    return function () {
        console.log(message);
        return func.apply(this, arguments);
    }
}

hello = logFactory(hello, "Some log message");

这不会让您获得任何数据同时它正在被函数操纵或改变函数内部发生的事情(尽管您可以捕获参数并在传递它们之前修改它们,并且你可以捕获返回值并在返回之前修改它).

This won't let you get any data while it is being manipulated by the function though or change what happens inside the function (although you can capture the arguments and modify them before passing them on, and you can capture the return value and modify it before returning it).