How to check that ES6 “variable” is constant?

前端 未结 4 1476
一整个雨季
一整个雨季 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 18:19

    Just check if your reassignment actually did something:

    var isConst = function(name, context) {
      // does this thing even exist in context?
      context = context || this;
      if(typeof context[name] === "undefined") return false;
      // if it does exist, a reassignment should fail, either
      // because of a throw, or because reassignment does nothing.
      try {
        var _a = context[name];
        context[name] = !context[name];
        if (context[name] === _a) return true;
        // make sure to restore after testing!
        context[name] = _a;
      } catch(e) { return true; }
      return false;
    }.bind(this);
    

    You need the try/catch because reassign Could throw an exception (like in Firefox), but when it doesn't (like in Chrome), you just check whether your "this always changes the value" reassignment actually did anything.

    A simple test:

    const a = 4;
    var b = "lol";
    isConst('a'); // -> true
    isConst('b'); // -> false
    

    And if you declare the consts in different context, pass that context in to force resolution on the correct object.

    downside: this won't work on vars declared outside of object scopes. upside: it makes absolutely no sense to declare them anywhere else. For instance, declaring them in function scope makes the const keyword mostly useless:

    function add(a) {
      return ++a;
    }
    
    function test() {
      const a = 4;
      console.log(add(a));
    }
    
    test(); // -> 5
    

    Even though a is constant inside test(), if you pass it to anything else, it's passed as a regular mutable value because it's now just "a thing" in the arguments list.

    In addition, the only reason to have a const is because it does not change. As such, constantly recreating it because you're calling a function that makes use of it more than once, means your const should live outside the function instead, so again, we're forced to put the variable in an object scope.

提交回复
热议问题