問題描述
有什么方法可以關閉我的 JavaScript 代碼中的所有 console.log
語句以進行測試?
Is there any way to turn off all console.log
statements in my JavaScript code, for testing purposes?
推薦答案
在腳本中重新定義 console.log 函數.
Redefine the console.log function in your script.
console.log = function() {}
就是這樣,沒有更多消息要控制臺.
That's it, no more messages to console.
擴展 Cide 的想法.一個自定義記錄器,您可以使用它來從您的代碼中切換登錄/關閉.
Expanding on Cide's idea. A custom logger which you can use to toggle logging on/off from your code.
從我的 Firefox 控制臺:
From my Firefox console:
var logger = function()
{
var oldConsoleLog = null;
var pub = {};
pub.enableLogger = function enableLogger()
{
if(oldConsoleLog == null)
return;
window['console']['log'] = oldConsoleLog;
};
pub.disableLogger = function disableLogger()
{
oldConsoleLog = console.log;
window['console']['log'] = function() {};
};
return pub;
}();
$(document).ready(
function()
{
console.log('hello');
logger.disableLogger();
console.log('hi', 'hiya');
console.log('this wont show up in console');
logger.enableLogger();
console.log('This will show up!');
}
);
如何使用上面的記錄器"?在您的就緒事件中,調用 logger.disableLogger 以便不記錄控制臺消息.在要將消息記錄到控制臺的方法中添加對 logger.enableLogger 和 logger.disableLogger 的調用.
How to use the above 'logger'? In your ready event, call logger.disableLogger so that console messages are not logged. Add calls to logger.enableLogger and logger.disableLogger inside the method for which you want to log messages to the console.
這篇關于如何快速方便地禁用我的代碼中的所有 console.log 語句?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!