How to check that ES6 “variable” is constant?

前端 未结 4 1499
一整个雨季
一整个雨季 2020-12-11 17:18

Does anyone know some tricks how to do it? I tried to use try-catch:

\"use strict\";

const a = 20;

var isConst = false;
try {
   var temp = a;         


        
4条回答
  •  不知归路
    2020-12-11 17:56

    I don't think there is, but I also don't think this is a big issue. I think it might be useful to have the ability to know if a variable is const, and this exists in some other languages, but in reality since you (or someone on a team) will be defining these variables, you'd know the scope and the type of the variables. In other words, no you can't, but it's also not an issue.

    The only case where it might be useful is if you could change the mutable property during runtime, and if changing this property had actual performance benefits; let, const, and var are treated roughly equally to the compiler, the only difference is that the compiler keeps track of const and will check assignments before it even compiles.

    Another thing to note is that just like let, const is scoped to the current scope, so if you have something like this:

    'use strict';
    
    const a = 12;
    
    // another scope
    {
      const a = 13;
    }
    

    it's valid. Just be careful that it will look up in higher scopes if you don't explicitly state const a = 13 in that new scope, and it will give a Read Only or Assignment error:

    'use strict';
    
    const a = 12;
    
    {
      a = 13; // will result in error
    }
    

提交回复
热议问题