这是一个旧问题,所有提供的答案都过于hackey(即过于 hacky),存在严重的跨浏览器问题,并且没有提供任何超级有用的东西。这个解决方案可以在每个浏览器中工作,并准确地报告所有控制台数据。无需hack,只需要一行代码查看CodePen。
var debug = console.log.bind(window.console)
按照以下方式创建开关:
isDebug = true // toggle this to turn on / off for global control
if (isDebug) var debug = console.log.bind(window.console)
else var debug = function(){}
然后只需按以下方式调用:
debug('This is happening.')
你甚至可以使用类似以下方式的开关接管console.log:
if (!isDebug) console.log = function(){}
如果你想要利用这个做些有用的事情,你可以添加所有控制台方法,并将其封装在一个可重复使用的函数中,不仅提供全局控制,还提供类级别的控制:
var Debugger = function(gState, klass) {
this.debug = {}
if (gState && klass.isDebug) {
for (var m in console)
if (typeof console[m] == 'function')
this.debug[m] = console[m].bind(window.console, klass.toString()+": ")
} else {
for (var m in console)
if (typeof console[m] == 'function')
this.debug[m] = function(){}
}
return this.debug
}
isDebug = true //global debug state
debug = Debugger(isDebug, this)
debug.log('Hello log!')
debug.trace('Hello trace!')
现在你可以将它添加到你的类中:
var MyClass = function() {
this.isDebug = true
this.debug = Debugger(isDebug, this)
this.debug.warn('It works in classses')
}
console.log
来输出信息,使用console.warn
来输出警告,使用console.error
来输出错误,而不是通过包装函数在console.log
中添加内容。 - Alvin Wongconsole
。为了实现这个目标,似乎只有使用包装器才是唯一的方法? - OpenGG