When used in practice, closures can create very elegant designs, allowing customization of the various calculation 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) { ... // 排序条件 });
In the same example, the map method of the array maps the original array to a new array according to the conditions defined in the function:
[1, 2, 3].map(function (element) { return element * 2; }); // [2, 4, 6]
Using functional 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 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 it is the parameter list, in call it is an independent parameter):
(function () { alert([].join.call(arguments, ';')); // 1;2;3 }).apply(this, [1, 2, 3]);
There is another very important application of closures - Delayed calls:
var a = 10; setTimeout(function () { alert(a); // 10, after one second }, 1000);
And callback functions:
//... var x = 10; // only for example xmlHttpRequestObject.onreadystatechange = function () { // 当数据就绪的时候,才会调用; // 这里,不论是在哪个上下文中创建 // 此时变量“x”的值已经存在了 alert(x); // 10 }; //...
You can also create encapsulated scopes to hide helper objects:
var foo = {}; // 初始化 (function (object) { var x = 10; object.getX = function _getX() { return x; }; })(foo); alert(foo.getX()); // 获得闭包 "x" – 10
Summary
This article introduces more theoretical knowledge about ECMAScript-262-3, and I think , these basic theories help to understand the concept of closure in ECMAScript.
The above is the content of JavaScript closure part 3: usage of closure. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!