为什么我应该使用块范围而不是函数范围? [英] Why should I use block scope instead of function scope?

查看:64
本文介绍了为什么我应该使用块范围而不是函数范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

功能范围对我来说完全没问题已有20年了。现在我到处读,我应该使用 const 而不是 var 。我想这主要是因为它是一个新功能。为什么我更喜欢块范围?

Function scoping was perfectly fine for me for 2 decades. Now I read everywhere, that I should use let and const instead of var. I guess this is mostly because it's a new feature. Why should I prefer block scope?

推荐答案

const 具有明显优势这是一个不断的约束。 有一个临时死区,禁止重新声明同一范围内的标识符,因此有助于防止出现某些错误。

const has the obvious advantage that it's a constant binding. let has a temporal dead zone, and its forbidden to redeclare an identifier in the same scope, so it helps to prevent certain mistakes.

除此之外,当你不需要块范围时继续使用 var 没有任何问题。

Apart from those, there's nothing wrong with continuing to use var when you don't need a block scope.

这篇关于为什么我应该使用块范围而不是函数范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆