将代码附加到现有功能的末尾 [英] Append code to the end of an existing function

查看:75
本文介绍了将代码附加到现有功能的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当函数foo()触发时,我都需要触发函数bar()。我无法控制函数foo或将来是否会更改。我经常遇到这种情况(我很讨厌)。

I need to trigger function bar() whenever function foo() fires. I have no control over function foo or whether it will change in the future. I have this situation regularly (and I hate it).

我编写了此函数,将代码添加到函数foo的末尾:

I wrote this function to add my code to the end of function foo:

function appendToFunction(fn,code){ 
if(typeof fn == 'function'){
    var fnCode = fn.toString() ;
    fnCode = fnCode.replace(/\}$/,code+"\n}") ;
    window.eval(fnCode);                    // Global scope
    return true ;
}
else{
    return false ;
}
}

例如:

appendToFunction(foo,"bar();");

这使我想到了一个可怕的主意-但却行得通。有人可以向我指出一个更好(更安全)的方向。

This strikes me as a terrible idea - but it works. Can somebody point me in a better (safer) direction please.

编辑: foo 不是特定功能,但是我要处理许多功能。它们不会在页面中动态更改。但是它们可能会不时更改(例如,表单验证要求)。

foo is not a specific function, but many functions that I wind up dealing with. They don't change dynamically in the page. But they may be changed (eg. form validation demands) from time to time.

解决方案
我选择了修改后的版本的亚当的答案。它不是完美的,但是比我拥有的要好:

Solution: I settled on a modified version of Adam's Answer. It's not perfect, but it's better than what I had:

var oldFoo = foo ;
foo = function(){
        var result = oldFoo.apply(this, arguments);
        bar();
        return result ;
}

NB。注意IE6 / 7中的某些本机函数,这些函数没有 .apply()方法。

NB. Watch out for some native functions in IE6/7 that don't have an .apply() method.

推荐答案

您可以使用调用原始函数的自定义函数来覆盖 foo

You can just override foo with a custom function that calls the original.

例如

var old_foo = foo;
foo = function() {
  old_foo();
  bar();
}

您还应该传递任何参数 foo 通过您的替换函数将其加入。

You should also pass any arguments foo takes into it via your replacement function.

这篇关于将代码附加到现有功能的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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