[Node. js] closures and high-level functions

Source: Internet
Author: User

[Node. js] closures and high-level functions
Introduction I recently found a problem: Some people who write JavaScript do not know much about the concept of functional programming. The following code snippets often make them incredible: OAuth2Server. prototype. authCodeGrant = function (check) {var self = this; return function (req, res, next) {new AuthCodeGrant (self, req, res, next, check );};}; the above piece comes from the open source project node-oauth2-server. This authCodeGrant prototype function involves two frequently used concepts in JS programming: Closure and higher-order functions (check variables are closed in this function, authCodeGrant can return the function, therefore, it is a high-level function. Closure is a function that references free variables. This referenced free variable will exist with this function, even if it has left the environment where it was created. How can we understand this free variable? Free variables are used in functions, but they are neither function parameters nor local variables of functions. What kind of variables are free variables? FreeVar in the following snippet is a free variable: function wrapper () {var freeVar = 42; function inner () {return 2 * freeVar;} return inner; before the closure is generated, it is not part of a function. When a function is called, the closure will be formed. The function will include this free variable in its own scope. That is to say, the free variable has nothing to do with the container that defines it, use the moment when a function is called as a time point to become a member in the function Context. Let's look at a confusing front-end example and add events cyclically: <button> 1st records </button> <button> 2nd records </button> <button> 3rd records </button> <button> 4th records </button> <button> 5th records </button> <button> 6th records </button> <script type = "text/javascript"> var buttonst_obj = document. getElementsByTagName ("button"); for (var I = 0, len = buttonst_obj.length; I <len; I ++) {buttonst_obj [I]. onclick = function () {alert (I) ;}</script> the result of the above snippet is that each Button is popped up with 6. Because there is no effective closure, because the closure has the feature of delay in value calculation, so when the function is executed, I = 6. If we change it to this way, I is used as the parameter of the outer function and is closed by the inner function. The result is also what we want: var buttonst_obj = document. getElementsByTagName ("button"); for (var I = 0, len = buttonst_obj.length; I <len; I ++) {buttonst_obj [I]. onclick = clickEvent (I);} function clickEvent (I) {return function () {console. log (I) ;}} Why? Because this clickEvent (I) High-order function uses I as a free variable (Note: I is not a parameter of the internal function or a part of the internal function, the closure has been formed and passed during click. The clickEvent (I) in the preceding loop event snippet of the high-order function is a high-order function. High-order functions: either one or more functions are accepted as input, or one function is output. Why do higher-order functions be used? To put it bluntly, it is for the closure. The high-order function that accepts functions as input can be used as a pattern constructor. For example, I have several sorting functions, such as fast sorting, heap sorting, and Hill sorting, then, I only need to provide a higher-order function to generate the sorters based on these sorts of sorting functions: // The sortingGenerator var sortingGenerator = function (sortFunc) {return function (args) {var arguments = []. slice. call (args); return sortFunc (arguments) ;}}; // introduce the Sorting Algorithm var heapSort = require ('heapsort '); var heapSorter = sortingGenerator (heapSort ); // use the heapSorter algorithm (4, 22, 44, 66, 77). Of course, this high-order function also outputs the Higher-Order Function of the function output function, which is the same as the above example. The function is also easy to understand: first, the free variable is closed, and different outputs will be generated according to it in future calls. For example, if I need a function that can be either square or cube, it is best to calculate everything. Then I need a higher-order function of the following parts: // calculate the n var powerOfN of m = function (n) {return function (m) {var res = 1; for (var I = 0; I <n; ++ I) {res * = m;} return res ;};// generate var powerOf2 = powerOfN (2); var powerOf3 = powerOfN (3) on demand ); // call the parameter passing console. log (powerOf2 (3); console. log (powerOf3 (2 ));

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.