Javascript 在 try 块中设置 const 变量

新手上路,请多包涵

ES6 中是否可以在严格模式下使用 try{}const 中设置变量?

 'use strict';

const path = require('path');

try {
    const configPath = path.resolve(process.cwd(), config);
} catch(error) {
    //.....
}

console.log(configPath);

这无法进行 lint,因为 configPath 定义超出范围。这似乎唯一可行的方法是:

 'use strict';

const path = require('path');

let configPath;
try {
    configPath = path.resolve(process.cwd(), config);
} catch(error) {
    //.....
}

console.log(configPath);

基本上,对于这种情况,有没有办法使用 const 而不是 let

原文由 Justin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 813
2 个回答

将变量声明为 const 需要您立即将其指向一个值,并且不能更改此引用。

这意味着您不能在一个地方定义它(在 try 之外)并在其他地方(在 try 之内)赋值。

 const test; // Syntax Error
try {
  test = 5;
} catch(err) {}

另一方面,创建它并在 try 块中为其赋值都可以。

 try {
  const test = 5; // this is fine
} catch(err) {}

但是, const 是块作用域的,比如 let ,所以如果你创建它并在你的 try 中给它一个值,它只会存在于块中那个范围。

 try {
  const test = 5; // this is fine
} catch(err) {}
console.log(test); // test doesn't exist here

因此,如果您需要在 try 之外访问此变量,则必须使用 let

 let configPath;
try {
   configPath = path.resolve(process.cwd(), config);
} catch(error) {
    //.....
}

console.log(configPath);

或者,虽然可能更令人困惑,但您可以使用 vartry 中创建一个变量,并在其外部使用它,因为 var 作用域内的作用域是函数不是块(并被 吊起):

 try {
   var configPath = path.resolve(process.cwd(), config);
} catch(error) {
    //.....
}

console.log(configPath);

原文由 nem035 发布,翻译遵循 CC BY-SA 3.0 许可协议

'use strict';

const path = require('path');

const configPath = (function() {
  try {
    return path.resolve(process.cwd(), config);
  } catch (error) {
    //.....
  }
})()

console.log(configPath);

原文由 steph643 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题