Jus*_*tin 23 javascript try-catch node.js ecmascript-6
在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这种情况?
nem*_*035 60
声明变量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);
或者,尽管可能更容易混淆,但您可以使用它var在其中创建变量并在try其外部使用它,因为它var是在函数范围内,而不是块(并且被提升):
try {
   var configPath = path.resolve(process.cwd(), config);
} catch(error) {
    //.....   
}
console.log(configPath);
'use strict';
const path = require('path');
const configPath = (function() {
  try {
    return path.resolve(process.cwd(), config);
  } catch (error) {
    //.....
  }
})()
console.log(configPath);
我会尝试使用临时变量,let并将其分配给/const之后的 var并“删除”临时变量。trycatch
'use strict';
let temp;
try {
  temp = path.resolve(process.cwd(), config);
} catch (error) {
  //.....   
}
const configPath = temp;
temp = undefined;
console.log(configPath);
| 归档时间: | 
 | 
| 查看次数: | 10777 次 | 
| 最近记录: |