EN
JavaScript - global variable protection / encapsulation
0
points
In this article, we would like to show you how to protect global variables from being accidentally set to a new value in JavaScript.
For example, by writing window.globalVariableName
, we are able to modify the global variable by accident if we do not put it behind some mechanism.
1. Correct solution
In this example, we present how to hide such global variables and protect them from being set to a new value.
// ONLINE-RUNNER:browser;
const object = new function () {
var counter = 0;
this.generateId = function () {
return ++counter;
};
};
console.log(object.generateId()); // Some action...
console.log(object.generateId()); // Some action...
console.log(object.generateId()); // Some action...
window.counter = 0;
console.log(object.generateId()); // Some action...
console.log(object.generateId()); // Some action...
2. Incrorrect solution
If we do not give a complicated name to a variable, there is a high chance that someone will create or refer to a global variable with the same name, damaging some part of the logic.
The example shows what can happen if we don't hide the counter
global variable.
// ONLINE-RUNNER:browser;
var counter = 0;
const generateId = function () {
return ++counter;
};
console.log(generateId()); // Some action...
console.log(generateId()); // Some action...
console.log(generateId()); // Some action...
window.counter = 0;
console.log(generateId()); // Some action...
console.log(generateId()); // Some action...