TEJacobsen TEJacobsen - 1 month ago 8
Javascript Question

How to make modular constants in javascript

i am a strong believer in encapsulation and this is hard using javascript. I want to be able to use constants that are not defined on a global level, but I am unable to accomplish this
Example:

html

<!DOCTYPE html>
<body>
<p>
<b>some examples</b>
</p>
<p>
<script>some.STRING</script><br>
<script>some.ARRAY.join(' - ')</script>
</p>
</body>


javascript

// some.js
var some = (function () {
return {
STRING: 'some string',
ARRAY: ["some", "data", "in", "an", "array"]
};
}
);


I would like the output to contain the two lines below

some string
some - data - in - an - array


jsfiddle: https://jsfiddle.net/p3kgpx70/4/

Answer

Here is a fiddle: https://jsfiddle.net/p3kgpx70/6/

// some.js
var some = (function () {
        return {
            STRING: 'some string',
            ARRAY: ["some", "data", "in", "an", "array"]
        };
    }
)();
element.innerHTML += some.STRING + "</br>";
element.innerHTML += some.ARRAY.join(' - ');

Error #1: IIFE must be wrapped in (function(){})()
Error #2: Putting an expression in a script doesn't add its value to the page. You must change the DOM to write value to the page. document.write(some.STRING) (by @Barmar) will throw an error if you put it in the p element. So, I used element.innerHTML after some variable definition to write the value.
#3 (not really an error: instead of var, you can use const to make some a constant.

Now, MORE IMMUTABLE!

// some.js
const object = {};
Object.defineProperty(object, "some", {get: function () {
        return {
            STRING: 'some string',
            ARRAY: ["some", "data", "in", "an", "array"]
        };
    }})

element.innerHTML += object.some.STRING + "</br>";
element.innerHTML += object.some.ARRAY.join(' - ');
object.some.STRING = 6;
console.log(object.some); // still not changed

In the first code block, if I set some.STRING = 6, the value will be changed. If you want to make it immutable, you must make object = {} a constant, then set property some's getter equals to your function. Everytime you get the value of object.some, it's still the same, even if you change the value of object.some like this: object.some.STRING = 6;. That's because of the magical function you invented. I wrote the wrapper for you.

In JavaScript, you can't set getter/setter of a global variable (no parent). Sorry.

Comments