Javascript - Override console.log and keep the old function

前端 未结 8 1331
春和景丽
春和景丽 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:28

    The best way to achieve what you want :

    // define a new console
    var console=(function(oldCons){
        return {
            log: function(text){
                oldCons.log(text);
                // Your code
            },
            info: function (text) {
                oldCons.info(text);
                // Your code
            },
            warn: function (text) {
                oldCons.warn(text);
                // Your code
            },
            error: function (text) {
                oldCons.error(text);
                // Your code
            }
        };
    }(window.console));
    
    //Then redefine the old console
    window.console = console;
    

提交回复
热议问题