Reputation: 1199
So in short, I have a module that I want to reuse multiple time on a page. In this module, I had a global const of an event name. The problem occurs at the declaration of the second usage of this module since the constant has already been declared. However, I can't move it into if/else since scoping will make the constant unable to be used elsewhere. What should I do?
Some simple code for my problem:
Module:
const THIS_IS_MY_EVENT = 'thisIsMyEvent';
// extra code down here
Page: (I use twig engine to include file but I don't think it's related)
<script src="/path/to/file.js">
<script src="/path/to/file.js">
This sure won't work in my case:
if (typeof (THIS_IS_MY_EVENT) == undefined) {
const .... //this will limit the scope of my const
}
Any help would be appreciated.
Upvotes: 5
Views: 2637
Reputation: 1074138
So in short, I have a module that I want to reuse multiple time on a page.
That sounds like the real problem to solve. Instead, import the module once, use a function within it twice. Modules generally shouldn't do anything on import (other than a bit of setup), only later when requested. That way, the global parts of the module will run once, creating the global const
(but it shouldn't be a global, it should be an exported const
from the module), and you won't have the problem.
But conditionally creating a global constant is an interesting problem. If you really want a global, you can use Object.defineProperty
to create it on window
with writable: false
. (This isn't quite the same. Properties on window
[the global object] are globals, but const
creates globals that aren't properties of window
. Still, probably close enough.)
Example:
"use strict";
if (typeof THIS_DOESNT_EXIST === "undefined") {
Object.defineProperty(window, "THIS_DOESNT_EXIST", {
value: "foo",
writable: false, // false is the default
configurable: false, // these are just for emphasis,
enumerable: true // or false, your call
});
}
console.log(THIS_DOESNT_EXIST);
THIS_DOESNT_EXIST = 42;
console.log(THIS_DOESNT_EXIST);
Upvotes: 4