gpt4 book ai didi

javascript - 对于函数范围的变量,用 const 代替 var?

转载 作者:行者123 更新时间:2023-12-03 01:56:12 25 4
gpt4 key购买 nike

我一直在阅读有关 Principle of Least Privilege 的内容我很困惑何时使用 letvarconst,特别是在函数级范围内。

read那:

Use let in places you know you need block scoping, and you've specifically thought about those implications. But continue to use var for variables that either cannot easily be block scoped, or which shouldn't be block scoped. There are going to be places in real world code where some variables are going to be properly scoped to the entire function, and for those variables, var is a better signal.

const 可以用于 var 作为函数范围的变量吗?例如:

function foo() {
const a = 10;

if (a > 2) {
let b = a * 3;
console.log(b);
}

if (a > 5) {
let c = a / 2;
console.log(c);
}

console.log(a);
}

而不是:

function foo() {
var a = 10;

if (a > 2) {
let b = a * 3;
console.log(b);
}

if (a > 5) {
let c = a / 2;
console.log(c);
}

console.log(a);
}

最佳答案

对于上面的代码,应使用 const 而不是 varlet,因为您使用的是变量 a 用于输出新变量(bc),而不是操纵或更改变量 a 本身。换句话说,值“a”在整个条件语句中保持不变。

  • Const:如果您根本不需要更改变量的值,请使用 const
  • Let:如果稍后必须更改变量的值,请使用“let”。
  • Var:避免使用var,因为“let”有一个重要的作用域机制,而“var”没有调用 block 作用域 .

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

Via - Mozilla Docs

关于javascript - 对于函数范围的变量,用 const 代替 var?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50219286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com