Are there constants in JavaScript?

2018-12-31 13:46发布

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条回答
路过你的时光
2楼-- · 2018-12-31 14:44

In JavaScript my practice has been to avoid constants as much as I can and use strings instead. Problems with constants appear when you want to expose your constants to the outside world:

For example one could implement the following Date API:

date.add(5, MyModule.Date.DAY).add(12, MyModule.Date.HOUR)

But it's much shorter and more natural to simply write:

date.add(5, "days").add(12, "hours")

This way "days" and "hours" really act like constants, because you can't change from the outside how many seconds "hours" represents. But it's easy to overwrite MyModule.Date.HOUR.

This kind of approach will also aid in debugging. If Firebug tells you action === 18 it's pretty hard to figure out what it means, but when you see action === "save" then it's immediately clear.

查看更多
冷夜・残月
3楼-- · 2018-12-31 14:45

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

function MY_CONSTANT() {
   return "some-value";
}


alert(MY_CONSTANT());
查看更多
伤终究还是伤i
4楼-- · 2018-12-31 14:45

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!).

查看更多
余生请多指教
5楼-- · 2018-12-31 14:45

If it is worth mentioning, you can define constants in angular using $provide.constant()

angularApp.constant('YOUR_CONSTANT', 'value');
查看更多
零度萤火
6楼-- · 2018-12-31 14:45

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.

查看更多
裙下三千臣
7楼-- · 2018-12-31 14:46

Are you trying to protect the variables against modification? If so, then you can use a module pattern:

var CONFIG = (function() {
     var private = {
         'MY_CONST': '1',
         'ANOTHER_CONST': '2'
     };

     return {
        get: function(name) { return private[name]; }
    };
})();

alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

CONFIG.MY_CONST = '2';
alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

CONFIG.private.MY_CONST = '2';                 // error
alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

Using this approach, the values cannot be modified. But, you have to use the get() method on CONFIG :(.

If you don't need to strictly protect the variables value, then just do as suggested and use a convention of ALL CAPS.

查看更多
登录 后发表回答