0

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();

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

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


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.

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.

How can i do this?

4

3 回答 3

3
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();
于 2013-05-17T08:05:45.030 回答
0

你为什么不创建一个新的function并放在里面,function test()这样当function test()被调用时,也会new function被调用..

例如

function test(){
 //code
 your_new_function();
}

function your_new_function(){
 //code
}
于 2013-05-17T07:49:51.707 回答
0

使用下面而不是制作同名功能

$(document).ajaxComplete(function() {
     // do your work
});

您不能创建两个同名的函数

于 2013-05-17T07:54:48.550 回答