暂时替换全局常量内部函数



Javascript中有没有办法暂时替换在外部作用域中定义的变量,但只在内部作用域中保留该值,就像在C++等其他语言中一样? 例如:

const debug = require('debug')('mymodule');
function example() {
// Temporarily replace main `debug` variable with value that
// only persists for this function
const debug = debug.extend('myfunction');
debug('should be in mymodule.myfunction');
}
debug('should be in mymodule');

当我尝试这样做时,Node 抱怨我在定义内部debug之前就访问了它,而我真正想做的是从父范围访问debug

可以使用本地定义覆盖范围较大的定义。 但是,这样做时,您将无法再访问范围更大的范围。

执行此操作时:

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');

可能有更好的解决方案,但我让它像这样工作:

debug = 'foo';
function example() {
const debug = this.debug + 'bar';
console.log(debug); // prints 'foobar'
}
example();
console.log(debug); // prints 'foo'

或者,如果要保留const关键字:

const debug = 'foo';
function example(debugRef) {
const debug = debugRef + 'bar';
console.log(debug); // prints 'foobar'
}
example(debug);
console.log(debug); // prints 'foo'

最新更新