Closures
Closures are the function inside function or combination of functions enclosed with referencing to its lexical environment.
<body>
<input type="button" value="Inquiry" onclick="account(1000)">
<script>
function account(a){
let accHolder = "Maxx";
let currentBal = 20000;
return withdrawl = function(){ // a closure function and uses its lexical
variables.
currentBal -= a;
alert(`Hi ! ${accHolder} Your Balance is : ${currentBal}`);
}();
}
</script>
</body>
Closures solves the 'this' keyword problem. And things private. In the above example, accHolder is a private property so that we can not access it directly outside the function.
And if we create with this keyword like this.accHolder this becomes globally accessible and this will create more problems.
To solve the problem we create functions to set the values and get the values and then return those functions so that we can access only those which we want to make public.
Let's take an example:
<script>
function account(){
let accHolder, currentBal; // these are private variables
let setDetails = function(_name,_bal){ // set the argument values
accHolder = _name;
currentBal = _bal;
}
let getName = function(){ // getName() is a closure
return accHolder; // returns name
}
let getBalance = function(){
return currentBal; // returns balance
}
return {setDetails, getName, getBalance}; // return functions
}
let acc = new account();
acc.setDetails("Maya","2000"); // setting the values
alert(acc.getName()+" "+acc.getBalance()); // print the values
alert(acc.accHolder); // we cant access properties like this. Error stmt
let acc1 = new account();
acc.setDetails("Jack","5000");
alert(acc.getName()+" "+acc.getBalance());
</script>
Here, we can not access accHolder and currentBal outside the funtion so
we create other funtions to set and get the values.
0 Comments