Reputation: 79218
I would like to do something like having cyclic dependencies. In order to do that, I have to resort to something like this:
// x.js
let y
exports.setY = function(_y) {
y = _y
}
// y.js
const x = require('./x')
x.setY(exports)
This sort of cyclic dependency problem happens all the time in database models, this referencing that, that referencing this. Ignore any ideas you might have on whether or not this specific use case of cyclic dependencies is a good idea, I'm more wondering if there is a way to convert a variable to a const in JavaScript after it has been declared. As in the let y
, after it is set, set it to a const.
Is anything like this possible? I would like to do this to get performance benefits as the key thing, I don't care about compile time checking benefits in this situation. Is there a way to make these two variables be compiled so they are maximally efficient?
Upvotes: 3
Views: 1783
Reputation: 2368
You could put your value in an object and freeze it:
From site:
The Object.freeze() method freezes an object. A frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed.
const test = { name: "" };
function setTestName(name) {
test.name = name;
Object.freeze(test);
}
Why you should use it is discussed here: Why would I need to freeze an object in JavaScript?
Upvotes: 3