Monday, 21 August 2017

What is a practical use for a closure in JavaScript?

Reference: Practical usage of closures



In practice closures may create elegant designs, allowing customization of various calculations, deferred calls, callbacks, creating encapsulated scope etc.



An example the sort method of arrays which accepts as an argument the sort-condition function:



[1, 2, 3].sort(function (a, b) {

... // sort conditions
});


Mapping functionals as the map method of arrays which maps a new array by the condition of the functional argument:



[1, 2, 3].map(function (element) {
return element * 2;
}); // [2, 4, 6]



Often it is convenient to implement search functions with using functional arguments defining almost unlimited conditions for search:



 someCollection.find(function (element) {
return element.someProperty == 'searchCondition';
});


Also, we may note applying functionals as, for example, a forEach method which applies a function to an array of elements:




[1, 2, 3].forEach(function (element) {
if (element % 2 != 0) {
alert(element);
}
}); // 1, 3


A function is applied to arguments (to a list of arguments — in apply, and to positioned arguments — in call):



(function () {

alert([].join.call(arguments, ';')); // 1;2;3
}).apply(this, [1, 2, 3]);


Deferred calls:



var a = 10;
setTimeout(function () {
alert(a); // 10, after one second
}, 1000);



Callback functions:



var x = 10;
// only for example
xmlHttpRequestObject.onreadystatechange = function () {
// callback, which will be called deferral ,
// when data will be ready;
// variable "x" here is available,

// regardless that context in which,
// it was created already finished
alert(x); // 10
};


Creation of an encapsulated scope for the purpose of hiding auxiliary objects:



var foo = {};
(function (object) {

var x = 10;
object.getX = function _getX() {
return x;
};
})(foo);
alert(foo.getX());// get closured "x" – 10

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...