Javascript在try块中设置const变量

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);
Run Code Online (Sandbox Code Playgroud)

这不能lint因为configPath在范围之外定义.这似乎有用的唯一方法是:

'use strict';

const path = require('path');

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

console.log(configPath);
Run Code Online (Sandbox Code Playgroud)

基本上,无论如何使用const而不是let这种情况?

nem*_*035 60

声明变量const需要您立即将其指向某个值,并且无法更改此引用.

这意味着您无法在一个地方(外部try)定义它,并在其他地方(内部)为其分配值try.

const test; // Syntax Error
try {
  test = 5; 
} catch(err) {}
Run Code Online (Sandbox Code Playgroud)

另一方面,创建它并在try块内给它一个值都很好.

try {
  const test = 5; // this is fine
} catch(err) {}
Run Code Online (Sandbox Code Playgroud)

但是,const就像块一样let,所以如果你创建它并在try块中给它一个值,它将只存在于该范围内.

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

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

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

console.log(configPath);
Run Code Online (Sandbox Code Playgroud)

或者,尽管可能更容易混淆,但您可以使用它var在其中创建变量并在try其外部使用它,因为它var是在函数范围内,而不是块(并且被提升):

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

console.log(configPath);
Run Code Online (Sandbox Code Playgroud)

  • 在这种情况下使用 var 是否令人不悦,我们现在应该总是尝试使用 let 和 const 吗?或者 var 仍然适用于这些用例吗? (4认同)
  • @hamncheez以这种方式使用var的主要问题是它给程序员带来了额外的认知负担。由于这种情况实际上是函数的全局变量(即使它是在较小的块中定义的),因此很难轻易地告诉该变量所泄漏到的所有范围。在较大的函数或使用相似(或相同)变量名的函数中,这尤其是个问题。var本质上需要更多的思维来理解其行为,因此更容易导致错误。 (3认同)
  • 我喜欢最后一个使用 `var` 的方法。不过,我总是将 `configPath = undefined;` 放在 catch 块中。特别是当块位于循环内时,避免它具有先前迭代的值。 (2认同)

ste*_*643 8

'use strict';

const path = require('path');

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

console.log(configPath);
Run Code Online (Sandbox Code Playgroud)

  • 我建议使用箭头匿名函数,以便“this”与外部上下文中的相同 (4认同)

yun*_*zen 5

我会尝试使用临时变量,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);
Run Code Online (Sandbox Code Playgroud)