[node. js] Closures and higher-order functions

Source: Internet
Author: User

Original address: http://www.moye.me/2014/12/29/closure_higher-order-function/

Introduction

Recently found a problem: part of the people who write JS, in fact, the concept of functional programming is not too understanding. The code snippet below often makes them feel incredible:

function (check) {  varthis;   return function (req, res, next) {    new  authcodegrant (self, req, res, next, check);   };};

The above snippet comes from the Open source project Node-oauth2-server, the Authcodegrant prototype function involves two commonly used concepts in JS programming: Closures and higher order functions (check variables are closed in this function, authcodegrant can return functions, So it's a high-order function.

Closed Package

A closure is a function that refers to a free variable. This quoted free variable will exist with this function, even if it has left the environment in which it was created.

How to understand this free variable?

A free variable is a variable that is used in a function but is not a function parameter or a local variable of a function.

What kind of variable is a free variable? The Freevar in the following fragment is a free variable:

function Wrapper () {    var freevar =;     function inner () {        return 2 * freevar;    }     return Inner;}

Free variables are not part of a function until the closure is generated. When a function is called, the closure is formed, and the function takes the free variable into its own scope, that is, the free variable is not related to the container that defines it, and the function is called at the point of time as a member of the function context.

Let's take a look at a confusing front-end example, loop Add event:

    <Button>1th Record</Button>    <Button>2nd record</Button>    <Button>3rd record</Button>    <Button>4th record</Button>    <Button>5th record</Button>    <Button>6th record</Button><Scripttype= "Text/javascript">      varButtonst_obj=document.getElementsByTagName ("Button");  for (varI= 0, Len=buttonst_obj.length; I<Len; I++) {Buttonst_obj[i].onclick= function() {alert (i);    }; }</Script>

The result of the above fragment is that each button pops up with 6. Because there is no effective closure, because the closure is a deferred evaluation feature, i = = 6 when the function is executed.

If we change it to this, I will be closed by the inner layer function as the parameter of the outer function, and the result is what we want:

var buttonst_obj = document.getElementsByTagName ("button");  for (var i = 0, len = buttonst_obj.length; i < Len; i++) {    = clickevent (i);} function clickevent (i) {    returnfunction  () {        console.log (i);}    }

Why? Because clickEvent(i) of this higher order function, it takes I as a free variable (note: I is not a parameter of the inner function, nor a part of the inner function), and the closure has been formed and passed at Click.

Higher order functions

The above loop event fragment is clickEvent(i) a higher-order function.

Higher-order functions satisfy: either accept one or more functions as input, or output a function

Why do you use higher-order functions? In a rough way, it's about closing the bag.

Higher order functions that accept functions as inputs

This high-order function can be used as a constructor for a pattern, such as: I have a number of sort functions such as quick sort/heap sort/hill sort, so I just need to provide a higher order function to generate a sequencer based on these sort functions:

//Sorting DevicevarSortinggenerator =function(sortfunc) {return function(args) {vararguments =[].slice.call (args); returnsortfunc (arguments); }};//introduction of sorting algorithmvarHeapsort = require (' Heapsort '));varHeapsorter =Sortinggenerator (heapsort);//using AlgorithmsHeapsorter (4, 22, 44, 66, 77);

Of course, this higher-order function also outputs the function

Higher order functions for output functions

As in the example above, the output of a function of the higher order function is also well understood: the first closure of the free variable, based on its future calls will produce a different output.

For example, I need a function that can be either squared, or cubic, preferably, and I need a higher-order function of the following fragment:

//calculates the n-th square of MvarPowerofn =function(n) {return function(m) {varres = 1;  for(vari = 0; I < n; ++i) {Res*=m; }        returnRes; } ;};//Build On DemandvarPOWEROF2 = Powerofn (2);varPOWEROF3 = Powerofn (3);//calling a parameterConsole.log (POWEROF2 (3)); Console.log (PowerOf3 (2));
Summary

With the combination of closures and higher-order functions, we can extract a programming pattern: The dynamic algorithm generator is implemented with minimal code by separating the >=2 parameters.

More articles please visit my blog new address: http://www.moye.me/

[node. js] Closures and higher-order functions

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.