1

我正在尝试从名为log4javascript.

我尝试了以下方法:

    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));
    };

但它不起作用,log.warn('test')例如,当我打电话时,它失败了Uncaught TypeError: object is not a function. 但如果我删除那部分代码,它就可以正常工作。

我做错了什么?

4

1 回答 1

2

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]);
}
于 2015-04-15T18:02:00.407 回答