所以我找到了一种包装方法
console.log
,这样当通过包装器调用时,它会保留调用位置的文件/行号。
但我想知道如何才能再次包裹它(如果实际的
logging
碰巧处于非常深的水平,可能会包裹好几次)。
class Debugger {
_log() {
return Function.prototype.bind.call(console.log, console);
}
log = this._log();
specialLog(msg: string) {
this.log('special: ' + msg);
}
}
const debug = new Debugger();
debug.log('hi'); // works perfect: correct file/line number
debug.specialLog('hi'); // line number -> where this.log() is called.
从这个示例代码中,我应该如何修改
specialLog
才能使其像 log
一样工作?.bind
、.apply
、.call
的组合,试图传递 console
上下文,但没有成功。
更新:
specialLog(msg: string) {
return this.log.bind(console, 'special ' + msg);
}
debug.specialLog('hi')(); // correct, but notice the extra '()'
这是我能得到的最接近的结果,但是有没有办法做到这一点而不必在调用后执行它?
更新2:jsfiddle
https://jsfiddle.net/mqa1duvr/
更新3:我需要它通过另一个包装器的原因:
实际的调试器看起来像这样:
class Debugger {
debug(...)
trace(...)
// and inside each these debug..trace..warn etc..
// there are set colors, timestamps, send log to server etc..
// then, finally after all the filters, there's the "final" log.
_log(...)
}
如果我可以让它在具有调用者上下文的同时深入遍历多个函数,那么我可以保持函数较小。
您可以使用
"special: "
设置默认参数(字符串 bind
)。所以这应该有效:
specialLog = Function.prototype.bind.call(console.log, console, "Special: ");
// ^^^^^^^^^^^^^^
说明:
当
specialLog
被调用时,传递给 console.log
的第一个参数将始终是 "Special: "
,所以如果你这样称呼它:
specialLog("Hello, world!");
就好像你打电话给
console.log
一样:
console.log("Special: ", "Hello, world!");
打印字符串:
"Special: Hello, world!"
,您想要的结果。
user7552(操作)编辑:
对于我的情况,它将是:
specialLog = Function.prototype.bind.call(this.log, console, "Special:");
使用
this.log
(调试器类内部的引用),而不是 console.log
。