是否可以在不修改原始代码的情况下向现有的 javascript 函数添加一些代码?
有一些javascript代码,例如
There is some javascript code, e.g.
function hello() {
}
function world() {
}
我想向它们添加一些日志记录代码,但我不想修改代码.我希望我可以在另一个文件中编写一些代码,它会在运行时修改函数.可以这样做吗?
I want to add some logging code to them, but I don't want to modify the code. I hope I can write some code in another file, and it will modify the functions at runtime. It is possible to do this?
更新
感谢您的两个回答,但我必须让这个问题更清楚.
Thanks for the two answers, but I have to make this question clearer.
hello
和 world
函数只是一些示例,实际上文件中有数百个函数,它是手动重新定义它们的实现.
The hello
and world
functions are just some samples, actually there are hundreds of functions in the file, it's implement to redefine them manually.
我正在寻找一种自动执行此操作的方法(类似于 java 中的 AspectJ).
I'm looking for a way to do this automatically (similar to AspectJ in java).
推荐答案
你不能修改函数,但是你可以包装它们,用包装器替换函数.
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).
相关文章