1

If I have a function like this:

 function showAlert() {
   alert("1");
 }

Is there a way to bind additional functionality to the same function in a different part of the page?

Like this:

 function showAlert() {
   alert("1");
   alert("2");
 }
Control Freak
  • 12,965
  • 30
  • 94
  • 145
  • Possible duplicate: http://stackoverflow.com/questions/296667/overriding-a-javascript-function-while-referencing-the-original – Adi Jul 09 '12 at 12:30
  • Why would you want to do that? That would make the code impossible to read! – Lee Taylor Jul 09 '12 at 12:30
  • Additional functionality to the same function, like a `close modal` function. Instead of binding to the same element that calls the function. – Control Freak Jul 09 '12 at 12:31

3 Answers3

4

You can overwrite the function with a new function that calls the old function.

 function showAlert() {
   alert("1");
 }

showAlert = (function (original){
 return function () {
   original();
   alert("2");
 }
}(showAlert));

showAlert();

​
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • ... and you even don't have to use `var showAlert = function()` for the first version, right. ) Nice one. – raina77ow Jul 09 '12 at 12:36
0

Well, you can simply redefine the function:

function showAlert() {
    alert("1");
}

var originalShowAlert = showAlert;

showAlert = function(){
    originalShowAlert();
    alert("2");
}

showAlert();
Graham
  • 6,484
  • 2
  • 35
  • 39
0

Since functions are treated simply as objects in JS, you can maintain an array of functions, then execute each function in a loop. This allows you to add any type of function that you want to the collection (and even remove them later if you keep the index), without breaking the execution train.

var funk = [];

funk.push(function showAlert1()
{
    alert("1");
});

funk.push(function showAlert2()
{

    alert("2");
});


funk.push(function showAlertFromMsg()
{
    alert("You passed " + this);

});


for(var i=0,len=funk.length; i<len; i++) funk[i].call("This is my message");
Grinn
  • 5,370
  • 38
  • 51