0

I am trying to figure out the best practices for scoping "constants" in JavaScript. To be clear, the reference to "constant" may be misleading. The question is aimed at how to properly scope such variables. How to declare and use them.

For example, I can write some code like:

var StormData = (function () {

/**
 * @constructor
 */
StormData = function () {

    this.atcID = undefined;
    this.name = undefined;
    this.entries = [];
};

StormData.prototype = {

    // Constants
    REVISION: "1.1"
];

return StormData;
})();

Unfortunately, since the code is an IIFE, JS says it can't find the variable "REVISION". I don't want to use ES2016 or more modern versions of JS with "const" since the support across browser/tools is uneven. I just want to use "plain" JavaScript - no ES6, no TS, etc. There are various convoluted ways to do this (just look around in SO). I could skip the IIFE, but that seems a poor solution. Short of a more modern version of JavaScript, is there a "best" way to do this?

rkwright
  • 447
  • 6
  • 21
  • why is there a return inside that block? guessing it is not complete code – epascarello May 22 '18 at 19:29
  • 2
    https://caniuse.com/#search=const shows that every modern browser is good with const. You can even use it on IE 11. – Trasiva May 22 '18 at 19:30
  • Possible duplicate of [Are there constants in JavaScript?](https://stackoverflow.com/questions/130396/are-there-constants-in-javascript) – Sterling Archer May 22 '18 at 19:32
  • 2
    You seem to be missing a closing curly brace after your prototype definition. Closing that and testing `new StormData().REVISION` outside the IIFE returns the value you're looking for. That said, is there a reason you aren't interested in at least using modern JS and transpiling down as necessary? – Fissure King May 22 '18 at 19:33
  • I would also suggest using [class](https://caniuse.com/#search=classes) instead of prototyping like that – Kevin Jantzer May 22 '18 at 20:30
  • Just to follow up n my own question, I found a partial answer to my "scoping" question https://stackoverflow.com/questions/32647215/declaring-static-constants-in-es6-classes. The key is to declare the "constants" AFTER the object is declared so the properties are appended to the object. The result is not immutable variables, but at least they are scoped. – rkwright May 23 '18 at 16:15

0 Answers0