Javascript - Override console.log and keep the old function

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

    Just enhancing the previous answer of @Ludovic to make his answer also support nodejs:

    // 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
            }
        };
    }(global.console !== undefined ? global.console : window.console));
    

提交回复
热议问题