对所有永远不会改变的变量使用const是否有意义?

ffx*_*sam 2 const ecmascript-6

鉴于这样的事情:

const audio = React.findDOMNode(this.refs.audio);
const seeker = React.findDOMNode(this.refs.seeker);
const {left, right} = seeker.getBoundingClientRect();
const seekToPerc = (event.clientX - left) / (right - left);

audio.currentTime = this.props.totalRunTime * seekToPerc;
Run Code Online (Sandbox Code Playgroud)

这是否过度使用const?我应该let在这里使用吗?

Bli*_*n67 5

const的使用取决于个人.如果你假装javascript是强类型的,那么大多数javascript引擎的优化效果最好.const因此看起来是个好主意.

一些事实.

  • MDN声明consts是块范围的let.这只适用于严格模式.
  • 必须为声明分配一个值.仅在严格模式下才为真.
  • Consts不能重新分配.在严格和正常情况下都是如此,但在正常的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
})();
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,在严格模式下使用const之间存在很大差异.除了严格模式之外,在任何东西中使用常量都是蛮干的.

性能.Chrome很早就采用了它,至少在3年前const我已经记忆犹新const.由于我专注于图形,因此性能至关重要.我推断a const会提供急需的性能优势,就像#define在C/C++中通过简单代码插入常量值一样.在那天结束的时候,我完全反对使用const,因为它表现糟糕.

从那以后它有所改善.

jsperf"Consts V Vars"

const在所有测试中,使用速度始终较慢,但它很小,而且距离调用太近.唯一的例外是块范围声明,它大约是var和的速度的1/3 let.一个令人惊讶的发现是,letChrome Beta现在非常快,一个月前我不会接近它,这个事实是我回答的原因.

OP问... 对所有永远不会改变的变量使用const是否有意义?

一年前我会说"永远不要用它".几个月前,我会说,"有一个很好的理由,但var更好".

现在我的答案肯定是使用常量,只要你想要一个变量永远不会改变.常量输出执行文字并且与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.
Run Code Online (Sandbox Code Playgroud)

以浏览器所经历的变化速度,以及最近几个月letconstChrome 上的性能变化.我怀疑常数将在今年年底之前完成变量.(请注意我使用的是Chrome Beta 47)

我所执行的测试没有为代码优化提供太多空间,因此我猜测在使用const中还有其他性能,这在测试中并不明显.

其本质上的常量是强类型的,这为javascript优化算法提供了一些用于提供额外性能的东西.

使用常量可以提高代码质量.Javascript(甚至严格模式)可以长时间隐藏错误,使用常量可以降低错误分配,意外类型转换等风险.

但是 我对const的使用发出了重大警告.只在严格模式下使用const,它在普通javascript中的行为是危险的,只会导致你的问题.