I have found this example of a closure on codeproject but it does not explain how it works.
function getMultiplier(multiplyBy){
function multiply(num){
return multiplyBy * num;
}
return multiply;
}
var multiplyByTwo = getMultiplier(2);
var multiplyByTen = getMultiplier(10);
var twoIntoFive = multiplyByTwo(5);
var tenIntoSix = multiplyByTen(6);
console.log(twoIntoFive); // 10
console.log(tenIntoSix); // 60
Now i am going to assume, with my C brain what is happening. Please correct me or give your explanation.
- functions in javascript can also be objects, so the inner function multiply(num) is a method of getMultiplier, looking from outside.
- var multiplyByTwo is assigned the return value of function getMultiplier when invoked with argument 2.
- when you call getMultiplier(2), javascript interpreter creates an object in memory based on the definition of getMultiplier().
- that object has a method multiply and it's address is assigned to variable multiplyByTwo.
- var twoIntoFive = multiplyByTwo(5); calls the getMultiplier(2) object's method multiply(num) with argument 5.
- that returns simple numeric 10 into variable twoIntoFive
- multiplyByTwo = 0; will make the garbage collector of javascript delete object getMultiplier(2) from memory.