Are there constants in JavaScript?

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

    Introducing constants into JavaScript is at best a hack.

    A nice way of making persistent and globally accessible values in JavaScript would be declaring an object literal with some "read-only" properties like this:

                my={get constant1(){return "constant 1"},
                    get constant2(){return "constant 2"},
                    get constant3(){return "constant 3"},
                    get constantN(){return "constant N"}
                    }
    

    you'll have all your constants grouped in one single "my" accessory object where you can look for your stored values or anything else you may have decided to put there for that matter. Now let's test if it works:

               my.constant1; >> "constant 1" 
               my.constant1 = "new constant 1";
               my.constant1; >> "constant 1" 
    

    As we can see, the "my.constant1" property has preserved its original value. You've made yourself some nice 'green' temporary constants...

    But of course this will only guard you from accidentally modifying, altering, nullifying, or emptying your property constant value with a direct access as in the given example.

    Otherwise I still think that constants are for dummies. And I still think that exchanging your great freedom for a small corner of deceptive security is the worst trade possible.

提交回复
热议问题