我最近在JavaScript中遇到了const关键字。据我所知,它是用来创建不可变变量的,我已经测试了,以确保它不能被重新定义(在Node.js中):
const x = 'const';
const x = 'not-const';
// Will give an error: 'constant 'x' has already been defined'
我意识到它还没有在所有浏览器上标准化——但我只对Node.js V8的环境感兴趣,我注意到某些开发人员/项目似乎非常喜欢它,当var关键字可以用于同样的效果时。
什么时候用const代替var比较合适?
它是否应该被用在每一个不存在的变量上
重新分配是声明的?
如果用var来代替,会有什么不同吗
Const还是反之?
当涉及到let和const(都是块作用域)之间的决定时,总是首选const,以便在代码中使用清楚。这样,如果您试图重新声明变量,就会得到一个错误。如果没有其他选择,只能重新声明它,只需转换为let。注意,正如Anthony所说,const值不是不可变的(例如,const对象的属性可以发生变化)。
When it comes to var, since ES6 is out, I never used it in production code and can't think of a use case for it. One point that might consider one to use it is JavaScript hoisting - while let and const are not hoisted, var declaration is. Yet, beware that variables declared with var have a function scope, not a block scope («if declared outside any function, they will be globally available throughout the program; if declared within a function, they are only available within the function itself», in HackerRank - Variable Declaration Keywords). You can think of let as the block scoped version of var.
你的问题有两个方面:使用const而不是var的技术方面是什么,以及这样做与人有关的方面是什么。
技术上的差异是显著的。在编译语言中,常量将在编译时被替换,它的使用将允许其他优化,如删除死代码,以进一步提高代码的运行时效率。最近(使用较少的术语)JavaScript引擎实际上编译JS代码以获得更好的性能,因此使用const关键字将通知它们上述优化是可能的并且应该完成。这将导致更好的性能。
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. However, not all information that never changes in the lifetime of a program needs to be declared with 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.