Reputation: 33
Where are constants created in a global scope stored in JavaScript?
For example, if I create a variable using: var var_example = '123'
, I can access it by window.var_example
.
However, if I create a const variable using: const const_example = '456'
, then how do I access it?
I need this to create an immutable/read-only global variable in a function.
I can create an ordinary global variable in a function using: window.in_function_var = 'global variable'
, but I don’t know how to create a constant/immutable/read-only global variable in a function; it seems to me that this can be done by accessing a scope with constants and adding the desired variable there.
Upvotes: 2
Views: 212
Reputation: 419
You can try to define an immutable property for window object. But this is not the same as a constant. It will not be possible to change it, but there will be no same error when trying to change.
"use strict"
const CONST1 = 1;
function setGlobalConst() {
Object.defineProperty(window, "CONST2", {
enumerable: false,
configurable: false,
writable: false,
value: 2
});
};
setGlobalConst();
console.log("CONST1: " + CONST1);
console.log("CONST2: " + CONST2);
// no have error but not mutted
CONST2 = 3;
// error
CONST1 = 2;
Upvotes: 2
Reputation: 35253
Variables declared using the const
and let
not defined on window because the specification says so.
You could use Object.defineProperty()
to add a property to the window object. This will set writable: false
and configurable: false
by default
Object.defineProperty(window, "in_function_var", {
value: 'global variable'
})
console.log(in_function_var)
in_function_var = "updated"
console.log(in_function_var)
delete window.in_function_var
console.log(in_function_var)
In strict mode, it throws an error if you try to update or delete the property:
"use strict"
Object.defineProperty(window, "global_var", {
value: 'global variable'
})
try {
global_var = "updated"
} catch (e) {
console.error(e)
}
try {
delete window.global_var
} catch (e) {
console.error(e)
}
Upvotes: 2