How to quickly and conveniently disable all console.log statements in my code?

后端 未结 28 2585
深忆病人
深忆病人 2020-11-22 16:48

Is there any way to turn off all console.log statements in my JavaScript code, for testing purposes?

28条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 17:22

    This a hybrid of answers from SolutionYogi and Chris S. It maintains the console.log line numbers and file name. Example jsFiddle.

    // Avoid global functions via a self calling anonymous one (uses jQuery)
    (function(MYAPP, $, undefined) {
        // Prevent errors in browsers without console.log
        if (!window.console) window.console = {};
        if (!window.console.log) window.console.log = function(){};
    
        //Private var
        var console_log = console.log;  
    
        //Public methods
        MYAPP.enableLog = function enableLogger() { console.log = console_log; };   
        MYAPP.disableLog = function disableLogger() { console.log = function() {}; };
    
    }(window.MYAPP = window.MYAPP || {}, jQuery));
    
    
    // Example Usage:
    $(function() {    
        MYAPP.disableLog();    
        console.log('this should not show');
    
        MYAPP.enableLog();
        console.log('This will show');
    });
    

提交回复
热议问题