How to wrap a javascript function

Recently I wanted to modify a project, to wrap a javascript function, so that I could extend the functionality of that function without breaking the project it was assigned to.

After searching the web for a bit, I found this stackoverflow-post, which exactly fits my needs. Works perfectly and I also learned something new :).

Suppose the function looks something like this:

foo = function(arg1, arg2) {
    console.log('original function');
}

now you want to wrap that function, you do this:

foo = (function() {
    //this is important!
    //you need to save the old function,
    //to call it later.
    var cached_function = foo;

    return function(arg1, arg2) {
        console.log('modified function - START');

        //If you use call, you can pass the arguments as they are
        //If you use apply, you have to pass the arguments as an array
        var returnValue = cached_function.call(this, arg1, arg2);

        console.log('modified function - END');

        return returnValue;
    };
}());

Works perfectly. Found here.