2

There is some javascript code, e.g.

function hello() {
}
function world() {
}

I want to add some logging code to them, but I don't want to modify the code. I hope I can write some code in another file, and it will modify the functions at runtime. It is possible to do this?


Update

Thanks for the two answers, but I have to make this question clearer.

The hello and world functions are just some samples, actually there are hundreds of functions in the file, it's implement to redefine them manually.

I'm looking for a way to do this automatically (similar to AspectJ in java).

Luca Borrione
  • 16,324
  • 8
  • 52
  • 66
Freewind
  • 193,756
  • 157
  • 432
  • 708

4 Answers4

3

You can't modify functions, but you can wrap them and replace the function with the wrapper.

Such (see a live demo):

function logFactory(func, message) {
    return function () {
        console.log(message);
        return func.apply(this, arguments);
    }
}

hello = logFactory(hello, "Some log message");

This won't let you get any data while it is being manipulated by the function though or change what happens inside the function (although you can capture the arguments and modify them before passing them on, and you can capture the return value and modify it before returning it).

Brandon
  • 38,310
  • 8
  • 82
  • 87
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • See the Underscorejs method [wrap](http://underscorejs.org/#wrap) for a more robust version of this method. – Brandon Mar 06 '13 at 15:44
2

You could always use another function name and call the function you want to "extend"

function extendSomefunction(param) {
    somefunction(param);
    // additional things here
}

But another trick you can find here

Copied code:

var origParseFloat = parseFloat;
parseFloat = function(str) {
     alert("And I'm in your floats!");
     return origParseFloat(str);
}
Community
  • 1
  • 1
Ron van der Heijden
  • 14,803
  • 7
  • 58
  • 82
1

The only other option you have, besides wrapping the functions inside new versions, is to modify the JavaScript files before they leave your server. Either manually, as a build step, or on the fly via an HttpHandler. This is the most robust solution since it also catches private functions and private references that are not exposed for you to wrap at runtime. However, it requires a lot of work, so if the simple function wrapping answer above is sufficient, I heartily recommend it!

Brandon
  • 38,310
  • 8
  • 82
  • 87
-1

You could wrap the function and replace it with the wrapper:

var originalHello;
originalHello = hello;

hello = function () {
    // log your stuff
    console.log('fired before original hello is triggered');

    // call original hello with the current scope & arguments
    originalHello.apply(this, arguments);
}
klaasman
  • 856
  • 7
  • 15
  • Thanks but sorry, your answer is the same as the existing one: http://stackoverflow.com/a/15251112/342235 – Freewind Mar 06 '13 at 15:29