Skip to content

Instantly share code, notes, and snippets.

@bhaveshdaswani93
Created November 24, 2019 10:33
Show Gist options
  • Save bhaveshdaswani93/abd0c9187953ad0ed8d010c625cc24cd to your computer and use it in GitHub Desktop.
Save bhaveshdaswani93/abd0c9187953ad0ed8d010c625cc24cd to your computer and use it in GitHub Desktop.
lets understand how closure help in encapsulation
function encapEg() {
let protectedData = 0; // this is the protected data that we only want to allow read access not direct change it
const accessTheData = () => protectedData; // this function will exported
const updateData = ()=> protectedData++; // we want to update the protected data internall
setInterval(updateData,1000); //this is the logic to update the data
return {
accessTheData // we return the function that only allow to access the protected data
}
}
const obj = encapEg();
console.log(obj.accessTheData());
// In the above example we have varable protectData that has to protected means we dont want to give direct access to manipulate it,
// we want to provide read ability, so we have created a function accessData which return the value of protected variable, this is all
// possible because of closure as on execution the function encapEg, it will be removed from the stack but the protectedData will not
// be remove because it is refrenced by the accessTheData function and value will be save in the closure.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment