Javascript - Override console.log and keep the old function

前端 未结 8 1181
春和景丽
春和景丽 2021-01-12 08:49

I would like to override console.log and call it on my new function.

I try something like this but I get Uncaught TypeError: Illegal invocation:

相关标签:
8条回答
  • 2021-01-12 09:39

    You are invoking the console.log function on the window object. You should instead invoke it on the console object.

    console.log = function() {
      this.apply(console, arguments);
    }.bind(console.log);
    
    console.log('as');
    
    0 讨论(0)
  • 2021-01-12 09:42

    try this:

    var console={
        log: function(v){
            alert(v);
        }
    };
    console.log('hello world');
    

    UPD:

    check this:

    var originalConsole={
        log: (function(c){
            return function(v){
                c.log(v);
            };
        }(window.console))
    };
    var console={
        log: function(v){
            originalConsole.log('_original_');
            originalConsole.log(v);
        }
    };
    console.log('hello world');
    

    originalConsole stores required methods of original console object(only log in my example), then console is overrided with new one.

    UPD2

    var console=(function(c){
        return {
            log: function(v){
                c.log('_original_');
                c.log(v);
            }
        };
    }(window.console));
    console.log('hello world');
    

    I hope this will help you.

    0 讨论(0)
提交回复
热议问题