您可以使用本地定义覆盖更高范围的一个。但是这样做时,您将无法再访问更高范围的。
当你这样做时:
const debug = debug.extend('myfunction');
您无法访问debug.extend()
,因为本地debug
已定义,但尚未初始化。
最简单的解决方案是使用不同的命名局部变量。但是,如果您不想这样做并且想要保留对更高范围的访问权限,则必须将其副本保存到比您定义新的更高级别的块范围中的另一个变量,以便您然后可以访问两者。
const debug = require('debug')('mymodule');
function example() {
// in a scope higher than where we define new debug variable,
// save a copy of it so we can still access it
const oldDebug = debug;
// create another block scope to contain the new debug definition
// and not interfere with saving the previous one above
{
const debug = oldDebug.extend('myfunction');
debug('should be in mymodule.myfunction');
}
}
debug('should be in mymodule');
另一种处理此问题的经典方法是将debug
参数传递给您的函数并将参数命名为不同的名称。然后,您可以同时使用新值和旧值。
const debug = require('debug')('mymodule');
function example(oldDebug) {
const debug = oldDebug.extend('myfunction');
debug('should be in mymodule.myfunction');
}
example(debug);
debug('should be in mymodule');