const 的使用取决于个人。如果您假装 javascript 是强类型的,则大多数 javascript 引擎的优化效果最好。 const 因此似乎是个好主意。
一些事实。
- MDN 声明 const 是块范围的,如
let。这只是真的
在严格模式下。
- 必须在声明时为常量赋值。严格来说才是真的
模式。
- 无法重新分配常量。这在严格和正常情况下都是如此
但是在普通的javascript中,分配给一个常量会默默地失败
表示难以找到错误的来源。 (注意没有好的
不使用严格模式的论据)
以差异为例
function log(d){console.log(d);}
(function (){
if(true){
const a = 10; // correctly formed use of constant
const b; // does not fail
log(a); // 10;
log(b); // undefined
b = 10; // nothing happens. If you have forgoten this is a constant
// you will have a hard time knowing this assignment is failing
log(b); // undefined
}
// scope not respected
log(a); // 10 const should have block scope. This does not seem to be true
// in normal javascript
})();
// function in strict mode
// not this is an example only and can not run. It is a compilation of several functions
(function (){
"use strict";
if(true){
const a = 10;
const b; // SyntaxError: Unexpected token. Javascript parsing
// stops here and the function will never be called
a = 20; // TypeError: Assignment to constant variable
}
// scope is respected
log(a); // ReferenceError: a is not defined
})();
正如您所见,在严格模式下使用 const 与不使用 const 之间存在很大差异。在严格模式下使用常量是很鲁莽的。
性能。
Chrome 很早就采用了const,我记得至少在 3 年前使用过const。由于我专攻图形,因此性能至关重要。我推断const 将提供非常需要的性能优势,这与#define 在C/C++ 中通过简单的代码插入常量值实现的方式非常相似。可悲的是,到那天结束时,我完全反对使用 const,因为它的性能很糟糕。
从那以后它有所改善。
jsperf "Consts V Vars"
使用const 在所有测试中始终较慢,但它是微不足道的并且太接近调用。唯一的例外是块范围声明,它的速度大约是 var 和 let 的 1/3。一个令人惊讶的发现是 let 现在在 Chrome Beta 上非常快,一个月前我不会靠近它,这个事实就是我回答的原因。
OP 问...
对所有永远不会改变的变量使用 const 有意义吗?
一年前我会说“永远不要使用它”。几个月前我会说,“有充分的理由,但 var 更好”。
现在我的回答是,只要您希望变量永不改变,就绝对使用常量。常量 out 执行文字并且与 var 一样好。
const c = 10;
var v = 10;
var a = 10; // this is slower
var a = c; // this is 20% faster
var a = v; // this is about < 1% faster than const.
根据浏览器的变化速度,以及过去几个月 let 和 const在 Chrome 上的性能变化。我怀疑常量将在今年年底前执行 vars。 (请注意我使用的是 Chrome Beta 47)
我执行的测试没有为代码优化提供太多空间,所以我猜想使用const 有额外的性能,这在测试中并不明显。
常量本质上是强类型的,这为 javascript 优化算法提供了一些可用于提供额外性能的东西。
使用常量可以提高代码质量。 Javascript(甚至是严格模式)可以长时间隐藏错误,使用常量可以降低错误赋值、意外类型转换等风险。
但是
我对 const 的使用提出了很大的警告。 只能在严格模式下使用 const,它在普通 javascript 中的行为是危险的,只会给你带来问题。