+ 4
What is simplest example of closure.
2 Answers
+ 7
just to extend the answer by calvin I ll just add a bit about IIFE s (commonly used to create closures in javascript) .
IIFE ( immediately invoked function expression) as the name suggests, you call the function right after you define it, and save a line of invocation in ur code.
how, by using ( ) ( )
// just declared the function here
var func = function () {}
to
// declared and invoked at the same time
var func = ( function() {}) ()
slight modification to example by calvin
https://code.sololearn.com/WE1naP9kfp7k/?ref=app
+ 4
var calNums = function() {
var num = 0; // init private num to 0
return {
add: function(n) { // add input with private num
num += n;
},
sum: function() { // return private num
return num;
}
}
}
var inputNums = calNums();
inputNums.add(2); // private num + 2
inputNums.add(3);// private num + 3
inputNums.add(6);// private num + 6
inputNums.add(4);// private num + 4
inputNums.add(5);// private num + 5
var sum = inputNums.sum(); // output sum of private num with inputs
console.log(sum);
https://code.sololearn.com/W1PHsygEiV78/?ref=app