In actual use, the closure can create a very elegant design that allows multiple computations defined on funarg.
In actual use, the closure can create a very elegant design that allows you to customize multiple computing methods defined on funarg. The following is an example of array sorting. It accepts a sorting condition function as a parameter:
[1, 2, 3]. sort (function (a, B) {... // sorting condition });
In the same example, the array map method maps the original array to a new array based on the conditions defined in the function:
[1, 2, 3].map(function (element) { return element * 2;}); // [2, 4, 6]
Using function parameters, you can easily implement a search method and support unlimited search conditions:
someCollection.find(function (element) { return element.someProperty == 'searchCondition';});
There are also application functions, such as the common forEach method, which applies the function to each array element:
[1, 2, 3].forEach(function (element) { if (element % 2 != 0) { alert(element); }}); // 1, 3
By the way, the apply and call methods of function objects can also be used as application functions in functional programming. Here, we regard them as application functions -- functions applied to parameters (in apply, they are a list of parameters and independent parameters in call ):
(function () { alert([].join.call(arguments, ';')); // 1;2;3}).apply(this, [1, 2, 3]);
The closure also has another very important application-delayed calling:
var a = 10;setTimeout(function () { alert(a); // 10, after one second}, 1000);
There are also callback functions:
//... Var x = 10; // only for examplexmlHttpRequestObject. onreadystatechange = function () {// called only when data is ready; // here, no matter in which context you create // The value of the variable "x" already exists alert (x); // 10 };//...
You can also create an encapsulated scope to hide the secondary object:
Var foo = {}; // initialization (function (object) {var x = 10; object. getX = function _ getX () {return x ;}) (foo); alert (foo. getX (); // get the closure "x"-10
Summary
This article introduces