I have a special case to use javascript. There is a variable defined by var myVar=xxx. Then I want to protect this variable to be changed by other code. I know that I can define the variable with const at beginning but there is some reason I can't do that. So I am looking for a way to convert an existed variable to be a const variable. Not sure whether it is possible.
-
2You cannot. ........zerkms– zerkms2017-03-15 23:26:26 +00:00Commented Mar 15, 2017 at 23:26
3 Answers
You cannot change your var into a const, but assuming that myVar is defined on the global object you can make the binding final using Object.defineProperty:
var myVar = 'sacred-value'
Object.defineProperty(window, 'myVar', {
writable: false,
value: window.myVar
})
myVar = 'evil-value'
console.log(myVar) //=> 'sacred-value'
Note: I have assumed the window object is your global context here, but if you are executing in a non-browser environment you may need to use global instead.
4 Comments
var-declared global properties are already nonconfigurableeval)You can't change a var into a const.
You could store your variable in an object, mutate it, and then freeze the object with Object.freeze to prevent further mutations:
const variables = {
a: 'b'
};
variables.a = 'c';
Object.freeze(variables);
variables.a = 'd'; // does nothing
console.log(variables.a);
2 Comments
Object.freeze makes objects immutable. It doesn't affect variable binding, so it won't work for your use-case without storing your variable in an object.You cannot change the type of a variable declaration afterwards. However, you can introduce a new scope where you declare it as a constant:
var myVar = "xxx"; // assuming global scope
{
const myVar = window.myVar; // or `this.` or `global.` depending on your environment
… // your code here that will throw on assigning to `myVar`
}