JavaScript中的常量:什么时候使用它,有必要吗?

本文翻译自:Const in JavaScript: when to use it and is it necessary?

I've recently come across the const keyword in JavaScript. 我最近在JavaScript中遇到了const关键字。 From what I can tell, it is used to create immutable variables , and I've tested to ensure that it cannot be redefined (in Node.js): 据我所知,它用于创建不可变变量 ,并且我已进行测试以确保不能重新定义它(在Node.js中):

const x = 'const';
const x = 'not-const';

// Will give an error: 'constant 'x' has already been defined'

I realise that it is not yet standardized across all browsers - but I'm only interested in the context of Node.js V8 , and I've noticed that certain developers / projects seem to favor it heavily when the var keyword could be used to the same effect. 我意识到它尚未在所有浏览器上实现标准化-但是我只对Node.js V8感兴趣,并且我注意到某些开发人员/项目似乎在使用var关键字时非常喜欢它。同样的效果。

So my questions are: 所以我的问题是:

  • When is it appropriate to use const in place of var ? 什么时候使用const代替var合适?
  • Should it be used every time a variable which is not going to be re-assigned is declared? 是否应该在每次声明一个不会被重新分配的变量时使用它?
  • Does it actually make any difference if var is used in place of const or vice-versa? 如果使用var代替const ,实际上有什么区别呢?反之亦然?

#1楼

参考:https://stackoom.com/question/1R6jx/JavaScript中的常量-什么时候使用它-有必要吗


#2楼

Personal preference really. 个人喜好。 You could use const when, as you say, it will not be re-assigned and is constant. 如您所说,可以在不重新分配常量且常量的情况下使用const。 For example if you wanted to assign your birthday. 例如,如果您想分配生日。 Your birthday never changes so you could use it as a constant. 您的生日永远不会改变,因此您可以将其用作常量。 But your age does change so that could be a variable. 但是您的年龄确实发生了变化,因此可能会有所不同。


#3楼

In my experience I use const when I want to set something I may want to change later without having to hunt through the code looking for bits that have been hard coded eg A file path or server name. 根据我的经验,当我想要设置某些内容时,我可以使用const ,而以后无需浏览代码即可查找经过硬编码的位,例如文件路径或服务器名称。

The error in your testing is another thing though, you are tring to make another variable called x, this would be a more accurate test. 测试中的错误是另一回事,您正试图制作另一个名为x的变量,这将是一个更准确的测试。

const x = 'const';
x = 'not-const';

#4楼

2017 Update 2017更新

This answer still receives a lot of attention. 这个答案仍然引起很多关注。 It's worth noting that this answer was posted back at the beginning of 2014 and a lot has changed since then. 值得注意的是,该答案已于2014年初发布,此后发生了很多变化。 support is now the norm. 支持现已成为常态。 All modern browsers now support const so it should be pretty safe to use without any problems. 现在所有现代浏览器都支持const因此使用起来应该很安全,不会出现任何问题。


Original Answer from 2014 2014年的原始答案

Despite having fairly decent browser support , I'd avoid using it for now. 尽管有相当不错的浏览器支持 ,但我暂时避免使用它。 From MDN's article on const : 来自MDN关于const的文章

The current implementation of const is a Mozilla-specific extension and is not part of ECMAScript 5. It is supported in Firefox & Chrome (V8). 当前const的实现是Mozilla特定的扩展,不属于ECMAScript5。它在Firefox和Chrome(V8)中受支持。 As of Safari 5.1.7 and Opera 12.00, if you define a variable with const in these browsers, you can still change its value later. 从Safari 5.1.7和Opera 12.00开始,如果您在这些浏览器中使用const定义变量,则以后仍可以更改其值。 It is not supported in Internet Explorer 6-10, but is included in Internet Explorer 11. The const keyword currently declares the constant in the function scope (like variables declared with var). 它在Internet Explorer 6-10中不受支持,但在Internet Explorer 11中包含。const关键字当前在函数范围内声明常量(如用var声明的变量)。

It then goes on to say: 然后继续说:

const is going to be defined by ECMAScript 6, but with different semantics. const将由ECMAScript 6定义,但具有不同的语义。 Similar to variables declared with the let statement, constants declared with const will be block-scoped. 与用let语句声明的变量相似,用const声明的常量将是块作用域的。

If you do use const you're going to have to add in a workaround to support slightly older browsers. 如果确实使用const ,则必须添加变通办法以支持稍旧的浏览器。


#5楼

There are two aspects to your questions: what are the technical aspects of using const instead of var and what are the human-related aspects of doing so. 您的问题有两个方面:使用const而不是var的技术方面是什么,以及与人相关的方面是什么。

The technical difference is significant. 技术差异很大。 In compiled languages, a constant will be replaced at compile-time and its use will allow for other optimizations like dead code removal to further increase the runtime efficiency of the code. 在编译语言中,常量将在编译时被替换,并且常量的使用将允许其他优化(如删除无效代码)以进一步提高代码的运行效率。 Recent (loosely used term) JavaScript engines actually compile JS code to get better performance, so using the const keyword would inform them that the optimizations described above are possible and should be done. 最近的(松散使用的术语)JavaScript引擎实际上会编译JS代码以获得更好的性能,因此使用const关键字将告知它们上述优化是可能的,应该进行。 This results in better performance. 这导致更好的性能。

The human-related aspect is about the semantics of the keyword. 与人有关的方面与关键字的语义有关。 A variable is a data structure that contains information that is expected to change. 变量是一种数据结构,其中包含预期会更改的信息。 A constant is a data structure that contains information that will never change. 常数是一种数据结构,其中包含永远不变的信息。 If there is room for error, var should always be used. 如果有错误的余地,则应始终使用var However, not all information that never changes in the lifetime of a program needs to be declared with const . 但是,并非所有在程序生存期内从未改变的信息都需要使用const声明。 If under different circumstances the information should change, use var to indicate that, even if the actual change doesn't appear in your code. 如果在不同的情况下信息应该更改,则即使实际更改未出现在代码中,也请使用var进行指示。


#6楼

You have great answers, but let's keep it simple. 您有很好的答案,但让我们保持简单。

const should be used when you have a defined constant (read as: it won't change during your program execution). 当您有一个已定义的常量时,应使用const (读为:在程序执行期间它不会更改)。

For example: 例如:

const pi = 3.1415926535

If you think that it is something that may be changed on later execution then use a var . 如果您认为在以后执行时可能会对其进行更改,请使用var

The practical difference, based on the example, is that with const you will always asume that pi will be 3.14[...], it's a fact. 根据示例,实际的区别在于使用const您总是会假设pi为3.14 [...],这是事实。

If you define it as a var , it might be 3.14[...] or not. 如果将其定义为var ,则可能不是3.14 [...]。

For a more technical answer @Tibos is academically right. 对于更多的技术答案,@ Tibos在学术上是正确的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值