Failing to override JS functions

125 views Asked by At

I'm trying to override some functions from a lib called log4javascript.

I tried the following:

    var _logFatal = log.fatal;
    var _logError = log.error;
    var _logWarn = log.warn;
    var _logDebug = log.debug;

    log.fatal = function(message){
        return _logFatal(stackTrace(message));
    };

    log.error = function(message){
        return _logError(stackTrace(message));
    };

    log.warn = function(message){
        return _logWarn(stackTrace(message));
    };

    log.debug = function(message){
        return _logDebug(stackTrace(message));
    };

But it doesn't work, when I call log.warn('test') for instance, it fails with Uncaught TypeError: object is not a function. But it works fine if I remove that part of the code.

What did I do wrong?

1

There are 1 answers

1
Jonathan.Brink On BEST ANSWER

What you are trying to do is what I've seen called "monkey-patching".

I believe the problem you are having is that you are not invoking the functions you are trying to extend with the correct scope.

Try this pattern:

var fnPreviousFatal = log.fatal;
log.fatal = function(message) {
    fnPreviousFatal.apply(this, [message]);
}