w00
w00

Reputation: 26772

Invoke two functions with the same name

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?

Upvotes: 0

Views: 263

Answers (3)

Yoshi
Yoshi

Reputation: 54649

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

Upvotes: 3

Manish Jangir
Manish Jangir

Reputation: 505

Use below instead of making same name function

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

You can't create two functions of same name

Upvotes: 0

Lian
Lian

Reputation: 1629

Why don't you create a new function and put inside the function test() so that when the function test() is called then the new function is called too..

e.g.

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

function your_new_function(){
 //code
}

Upvotes: 0

Related Questions