调用两个具有相同名称的功能 [英] Invoke two functions with the same name

查看:123
本文介绍了调用两个具有相同名称的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之,我想用一个较新的函数覆盖javascript函数,但是在该较新的函数中,我希望能够调用旧的javascript函数.例如:

In short i want to overwrite a javascript function with a newer one, but in that newer function i want to be able to call the old one. So for example:

function test()
{
    alert('original');
}

// then some time later
function test()
{
    alert('new function');
}

// call function
test();

在这种情况下,仅最后一个test()被调用.因此new function会收到警报.

In this case only the last test() is invoked. So the new function is alerted.

但是还有一种方法可以调用第一个test()方法吗?所以这两个test()函数都被调用?

But is there a way to call the first test() method aswell? SO both test() function get invoked?

我需要这个的原因是因为Web应用程序生成了onSave()方法.通过Ajax保存表单时会触发此功能.

The reason i need this is because a web application generates an onSave() method. This function is triggered when a form is saved through Ajax.

保存表单时,我想做一些其他事情,但我不能只更改原始的onSave()函数.这就是为什么我正在寻找一种扩展方式.

I want to do some additional things when the form is saved but i can't just change the original onSave() function. That is why i'm looking for a way to extend it.

我该怎么做?

推荐答案

function test()
{
    console.log('original');
}


var test = function (oldFn) {
  // /\
  //  -------
  //        \/
  return function () { // <- return a new function which will get stored in `test`
    oldFn();                     // use the passed `oldFn`
    console.log('new function'); // the new code
  };
}(test); // <- pass in the old function, we do this, to avoid reference problems

// call function
test();

这篇关于调用两个具有相同名称的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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