我最近在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.
当涉及到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有三个有用的东西(除了它与let共享的作用域改进):
它为以后阅读代码的人记录了该值不能更改。
它可以防止您(或任何跟随您的人)更改值,除非他们返回并有意更改声明。
它可以节省JavaScript引擎在优化方面的一些分析。例如,你已经声明了值不能改变,所以引擎不需要做功来确定值是否改变,所以它可以决定是否基于值不变进行优化。
你的问题:
什么时候用const代替var比较合适?
你可以在任何时候声明一个值永远不变的变量。你认为这是否合适完全取决于你/你的团队的偏好。
每次声明一个不会被重新赋值的变量时都应该使用它吗?
这取决于你/你的团队。
如果使用var代替const '或反之亦然,它是否有任何区别?
Yes:
var and const have different scope rules. (You might have wanted to compare with let rather than var.) Specifically: const and let are block-scoped and, when used at global scope, don't create properties on the global object (even though they do create globals). var has either global scope (when used at global scope) or function scope (even if used in a block), and when used at global scope, creates a property on the global object.
See my "three useful things" above, they all apply to this question.