我制作了以下课程来“劫持”该console.log
功能。这背后的原因是我想
动态地添加和删除值。它将用于调试目的,因此函数调用的来源 console.log()
很重要。在下面的代码中,我将在评论中解释我的逻辑。
export class ConsoleLog {
private _isActive = false;
private _nativeLogFn: any;
constructor() {
// ----------------------
// Store the native console.log function, so it can be restored later
// ----------------------
this._nativeLogFn = console.log;
}
public start() {
if (!this._isActive) {
// ----------------------
// Create a new function as replacement for the native console.log
// function. *** This will be the subject of my question ***
// ----------------------
console.log = console.log.bind(console, Math.random());
this._isActive = true;
}
}
public stop() {
if (this._isActive) {
// Restore to native function
console.log = this._nativeLogFn;
this._isActive = false;
}
}
}
这种设置的问题在于,新功能是以静态形式分配的。
// Function random() generates a number at the moment I assign the function.
// Let's say it's the number *99* for example sake.
console.log.bind(console, Math.random());
每次console.log(...)
调用时,都会输出99。所以它几乎是静态的。(领先于你:不,我的目标不是输出随机数,哈哈,但我只是用它来测试输出是否是动态的。)。
烦人的部分是,使用该函数
console.log.bind
是我发现实际保留原始调用者和行号的唯一方法。
我写了以下简单的测试。
console.log('Before call, active?', 'no'); // native log
obj.start(); // Calls start and replaces the console.log function
console.log('foo'); // This will output 'our' 99 to the console.
console.log('bar'); // This will output 'our' 99 again.
obj.stop(); // Here we restore the native console.log function
console.log('stop called, not active'); // native log again
// Now if I call it again, the random number has changed. What is
// logical, because I re-assign the function.
obj.start(); // Calls start and replaces the console.log function
console.log('foo'); // This will output N to the console.
// But then I have to call start/log/stop all the time.
问题:如何在运行时向 console.log 添加值而不会丢失原始调用者文件名和行号......并且一旦使用 start() 启动此类,又不会打扰库使用者。
编辑:添加了一个 plkr:https ://embed.plnkr.co/Zgrz1dRhSnu6OCEUmYN0