Search code examples
javascriptdom-events

Check for function called


Just wondering if there is anyway to fire some code when a function is called, without adding the code to the function, for example:

function doSomething(){
    //Do something
}

//Code to call when doSomething is called

Solution

  • You can wrap the function :

    (function(){
       var oldFunction = doSomething;
       doSomething = function(){
           // do something else
           oldFunction.apply(this, arguments);
       }
    })();
    

    I use an IIFE here just to avoid polluting the global namespace, it's accessory.