Are there constants in JavaScript?

后端 未结 30 2571
抹茶落季
抹茶落季 2020-11-22 08:53

Is there a way to use constants in JavaScript?

If not, what\'s the common practice for specifying variables that are used as constants?

相关标签:
30条回答
  • 2020-11-22 09:25

    Okay, this is ugly, but it gives me a constant in Firefox and Chromium, an inconstant constant (WTF?) in Safari and Opera, and a variable in IE.

    Of course eval() is evil, but without it, IE throws an error, preventing scripts from running.

    Safari and Opera support the const keyword, but you can change the const's value.

    In this example, server-side code is writing JavaScript to the page, replacing {0} with a value.

    try{
        // i can haz const?
        eval("const FOO='{0}';");
        // for reals?
        var original=FOO;
        try{
            FOO='?NO!';
        }catch(err1){
            // no err from Firefox/Chrome - fails silently
            alert('err1 '+err1);
        }
        alert('const '+FOO);
        if(FOO=='?NO!'){
            // changed in Sf/Op - set back to original value
            FOO=original;
        }
    }catch(err2){
        // IE fail
        alert('err2 '+err2);
        // set var (no var keyword - Chrome/Firefox complain about redefining const)
        FOO='{0}';
        alert('var '+FOO);
    }
    alert('FOO '+FOO);
    

    What is this good for? Not much, since it's not cross-browser. At best, maybe a little peace of mind that at least some browsers won't let bookmarklets or third-party script modify the value.

    Tested with Firefox 2, 3, 3.6, 4, Iron 8, Chrome 10, 12, Opera 11, Safari 5, IE 6, 9.

    0 讨论(0)
  • 2020-11-22 09:25

    The keyword 'const' was proposed earlier and now it has been officially included in ES6. By using the const keyword, you can pass a value/string that will act as an immutable string.

    0 讨论(0)
  • 2020-11-22 09:26

    Yet there is no exact cross browser predefined way to do it , you can achieve it by controlling the scope of variables as showed on other answers.

    But i will suggest to use name space to distinguish from other variables. this will reduce the chance of collision to minimum from other variables.

    Proper namespacing like

    var iw_constant={
         name:'sudhanshu',
         age:'23'
         //all varibale come like this
    }
    

    so while using it will be iw_constant.name or iw_constant.age

    You can also block adding any new key or changing any key inside iw_constant using Object.freeze method. However its not supported on legacy browser.

    ex:

    Object.freeze(iw_constant);
    

    For older browser you can use polyfill for freeze method.


    If you are ok with calling function following is best cross browser way to define constant. Scoping your object within a self executing function and returning a get function for your constants ex:

    var iw_constant= (function(){
           var allConstant={
                 name:'sudhanshu',
                 age:'23'
                 //all varibale come like this
    
           };
    
           return function(key){
              allConstant[key];
           }
        };
    

    //to get the value use iw_constant('name') or iw_constant('age')


    ** In both example you have to be very careful on name spacing so that your object or function shouldn't be replaced through other library.(If object or function itself wil be replaced your whole constant will go)

    0 讨论(0)
  • 2020-11-22 09:28

    Group constants into structures where possible:

    Example, in my current game project, I have used below:

    var CONST_WILD_TYPES = {
        REGULAR: 'REGULAR',
        EXPANDING: 'EXPANDING',
        STICKY: 'STICKY',
        SHIFTING: 'SHIFTING'
    };
    

    Assignment:

    var wildType = CONST_WILD_TYPES.REGULAR;
    

    Comparision:

    if (wildType === CONST_WILD_TYPES.REGULAR) {
        // do something here
    }
    

    More recently I am using, for comparision:

    switch (wildType) {
        case CONST_WILD_TYPES.REGULAR:
            // do something here
            break;
        case CONST_WILD_TYPES.EXPANDING:
            // do something here
            break;
    }
    

    IE11 is with new ES6 standard that has 'const' declaration.
    Above works in earlier browsers like IE8, IE9 & IE10.

    0 讨论(0)
  • 2020-11-22 09:28

    My opinion (works only with objects).

    var constants = (function(){
      var a = 9;
    
      //GLOBAL CONSTANT (through "return")
      window.__defineGetter__("GCONST", function(){
        return a;
      });
    
      //LOCAL CONSTANT
      return {
        get CONST(){
          return a;
        }
      }
    })();
    
    constants.CONST = 8; //9
    alert(constants.CONST); //9
    

    Try! But understand - this is object, but not simple variable.

    Try also just:

    const a = 9;
    
    0 讨论(0)
  • 2020-11-22 09:28

    I use const instead of var in my Greasemonkey scripts, but it is because they will run only on Firefox...
    Name convention can be indeed the way to go, too (I do both!).

    0 讨论(0)
提交回复
热议问题