是否有可能增加一些code到现有的JavaScript功能,而无需修改原来的code吗? [英] Is it possible to add some code to existing javascript functions without modify original code?

查看:118
本文介绍了是否有可能增加一些code到现有的JavaScript功能,而无需修改原来的code吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一些JavaScript的code,例如

There is some javascript code, e.g.

function hello() {
}
function world() {
}

我想一些日志记录code添加到他们,但我不希望修改code。我希望我能写一些code在另一个文件中,它将在运行时修改的功能。这是可能做到这一点?

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.

你好全球功能只是一些样品中,居然有上百种功能的文件,它的实现手动重新定义它们。

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.

我在寻找一种能够自动做到这一点(类似的AspectJ在Java)。

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).

这篇关于是否有可能增加一些code到现有的JavaScript功能,而无需修改原来的code吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆