- In this example, we will be declaring a closure which would eventually access an outer variable balance from the outer function.
- After using the outer variable in inner most function, that particular closure will help us to deduct 100 from it, each time whenever that outer function is called.
Explanation: In the above example, currentbalance() can access outer variable balance hence balance is deducted by 100 each time initaccount() method is called.
Example 2: Closures can be nested as well as in below example. Here in the example both outerfunction() and innerfunction() has access to counter variable , hence on calling Counter() both outerfunction() and innerfunction() increments the value of counter. In this context, we can say that closures have access to all outer function scopes.
Please Login to comment...