1

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从父范围访问。

4

2 回答 2

1

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

当你这样做时:

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');
于 2020-01-19T04:08:58.117 回答
0

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

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'

于 2020-01-19T03:27:22.527 回答