Are there constants in JavaScript?

后端 未结 30 2570
抹茶落季
抹茶落季 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:29

    ECMAScript 5 does introduce Object.defineProperty:

    Object.defineProperty (window,'CONSTANT',{ value : 5, writable: false });
    

    It's supported in every modern browser (as well as IE ≥ 9).

    See also: Object.defineProperty in ES5?

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

    In JavaScript, my preference is to use functions to return constant values.

    function MY_CONSTANT() {
       return "some-value";
    }
    
    
    alert(MY_CONSTANT());
    
    0 讨论(0)
  • 2020-11-22 09:29

    Rhino.js implements const in addition to what was mentioned above.

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

    For a while, I specified "constants" (which still weren't actually constants) in object literals passed through to with() statements. I thought it was so clever. Here's an example:

    with ({
        MY_CONST : 'some really important value'
    }) {
        alert(MY_CONST);
    }
    

    In the past, I also have created a CONST namespace where I would put all of my constants. Again, with the overhead. Sheesh.

    Now, I just do var MY_CONST = 'whatever'; to KISS.

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

    The const keyword is in the ECMAScript 6 draft but it thus far only enjoys a smattering of browser support: http://kangax.github.io/compat-table/es6/. The syntax is:

    const CONSTANT_NAME = 0;
    
    0 讨论(0)
  • 2020-11-22 09:32

    IE does support constants, sort of, e.g.:

    <script language="VBScript">
     Const IE_CONST = True
    </script>
    <script type="text/javascript">
     if (typeof TEST_CONST == 'undefined') {
        const IE_CONST = false;
     }
     alert(IE_CONST);
    </script>
    
    0 讨论(0)
提交回复
热议问题