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
。 你不能使用const
。 const
不允许你重新声明已声明的常量。 尽pipe像const
用const
声明对象一般是很好的做法,但这样做的关键是允许对象进行变异而不允许重新分配对象。 你重新分配对象(因此,击败const
的目的),所以使用let
来代替。
let path = require('path'); // Good to go!