+ 4

What is simplest example of closure.

31st Aug 2018, 6:30 AM
SHIVAM SHUKLA
SHIVAM SHUKLA - avatar
2 ответов
+ 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
31st Aug 2018, 12:09 PM
Morpheus
Morpheus - avatar
+ 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
31st Aug 2018, 7:32 AM
Calviղ
Calviղ - avatar