+ 2
What are closure functions in Javascript?
Why do we use closure functions and where they are implemented
1 Antwort
+ 1
Let's say you create some function which adds something to its parameter:
function addSome(num) {
var add = 10;
return add + num;
}
You can rewrite it with closure:
function addSome(num) {
var add = 10;
return _closure();
function _closure(){
return add + num;
}
}
Here _closure function still have add and num variables in its scope, so result of both addSome functions will be the same.
In more interesting case we can pass some function in another function and our passed function will have its scope.
Also you can write object code using closures:
var addObj ={};
(function (){
var add = 10;
addObj.addSome = function (num){
return add + num;
}
})();
addObj.addSome will return the same result as other addSome functions do.
Sample code https://code.sololearn.com/W8Ccs59u552h