JavaScript Closures
- JavaScript variables can belong to the local or global scope.
- Global variables can be made local (private) with closures.
- a closure is one way of supporting first class functions, it is an expression that can reference variables within its scope (when it was first declared), be assigned to a variable, be passed as an argument to a function, or be returned as a function result. Or
- a closure is a stack frame which is allocated when a function starts its execution, and not freed after the function returns.
example -
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
add();
add();
add();
// the counter is now 3
What I learnt in Lab class..
Create a separate function using JavaScript closure which accepts the tax percentage and
returns a function which accepts the amount and returns the amount after adding tax
percentage.
// closure is used to hide the inner implementation
function tax (taxPercentage){
var tPer = taxPercentage; //
assinging the parameter to a variable
//outer function implementation
return function netTax
(amount) //it is like a function inside a function
{
var nTax = amount+tPer; //
net tax is calculated adding the parameters
return nTax;
};
}
var f1 = tax(20); //calling the tax
method
console.log(f1(30));
Comments
Post a Comment