Javascript在一个try块内设置constvariables

是否有可能在ES6中使用const在严格模式下在try{}设置variables?

 'use strict'; const path = require('path'); try { const configPath = path.resolve(process.cwd(), config); } catch(error) { //..... } console.log(configPath); 

由于configPath被定义为超出范围,因此无法使用lint。 这似乎工作的唯一方法是通过做:

 'use strict'; const path = require('path'); let configPath; try { configPath = path.resolve(process.cwd(), config); } catch(error) { //..... } console.log(configPath); 

基本上,有反正使用const而不是let这种情况下?

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

意思是你不能在一个地方定义它(在try之外)并且在别的地方(在try )赋值。

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

使用let 你不能使用constconst不允许你重新声明已声明的常量。 尽pipe像constconst声明对象一般是很好的做法,但这样做的关键是允许对象进行变异而不允许重新分配对象。 你重新分配对象(因此,击败const的目的),所以使用let来代替。

 let path = require('path'); // Good to go!