yilmazhuseyin
yilmazhuseyin

Reputation: 6612

javascript function modification

I am trying to write a logger object which logs messages to screen. here is my code. http://github.com/huseyinyilmaz/javascript-logger in every function that needs to log something, I am writing loggerstart and loggerEnd functions at start and end of my functions. But I want to run thos codes automaticalls for every function. is there a way to modify Function prototype so every function call can run automatically. (I am not using any javascript framework.)

Upvotes: 2

Views: 124

Answers (2)

bezmax
bezmax

Reputation: 26132

EDIT: Rewritten the function to make it more modular

Well, this is a creepy way to do it, but I use this way sometimes when I need overriding some functions. It works well, allows any kind of customization and easy to understand (still creepy).

However, you will need to have all your functions stored in some kind of global object. See the example for details.

function dynamic_call_params(func, fp) {
    return func(fp[0],fp[1],fp[2],fp[3],fp[4],fp[5],fp[6],fp[7],fp[8],fp[9],fp[10],fp[11],fp[12],fp[13],fp[14],fp[15],fp[16],fp[17],fp[18],fp[19]);
}

function attachWrapperToFunc(object, funcName, wrapperFunction) {
    object["_original_function_"+funcName] = object[funcName];
    object[funcName] = function() {
        return wrapperFunction(object, object["_original_function_"+funcName], funcName, arguments);
    }
}

function attachWrapperToObject(object, wrapperFunction) {
    for (varname in object) {
        if (typeof(object[varname]) == "function") {
            attachWrapperToFunc(object, varname, wrapperFunction);
        }
    }
}

And some usage example:

var myProgram = new Object();
myProgram.function_one = function(a,b,c,d) {
    alert(a+b+c+d);
}
myProgram.function_two = function(a,b) {
    alert(a*b);
}

myProgram.function_three = function(a) {
    alert(a);
}

function loggerWrapperFunction(functionObject, origFunction, origFunctionName, origParams) {
    alert("start: "+origFunctionName);
    var result = dynamic_call_params(origFunction, origParams);
    alert("end: "+origFunctionName);
    return result;
}

attachWrapperToObject(myProgram,loggerWrapperFunction);
myProgram.function_one(1,2,3,4);
myProgram.function_two(2,3);
myProgram.function_three(5);

Output will be: start,10,end,start,6,end,start,5,end

So generally it allows you to wrap each function in some object automatically with a custom written wrapper function.

Upvotes: 4

dst
dst

Reputation: 1788

You could call every function with a wrapper function.

function wrapper(callback) {
    loggerstart();
    callback();
    loggerend();
}

And call it with wrapper(yourfunction);

Upvotes: 0

Related Questions