JS Higher order function

Source: Internet
Author: User

In a typical programming language, a function's arguments can only be primitive types or object references, and return values are just basic data types or object references. But in JavaScript, a function as a class citizen can be passed as a parameter or returned as a return value. The so-called higher-order function is the function that can be used as an argument or a function as the return value. These two situations have many application scenarios in the actual development, this article is the summary of several application scenarios that I encounter in the work study.

First, the callback function

Code reuse is one of the important criteria for measuring an application. The code reuse rate can be effectively improved by extracting the changed business logic from the wrapper in the callback function. For example, the ES5 adds a foreach method to an array, iterates through the arrays, and invokes the same function for each element.

Array == function (arr, fn) {    for (var0, len = arr.length; i < len; i++ {        fn (arr[i], I, arr);    }}

The callback function focuses the focus of the business on the callback function without having to repeatedly write the traversal code each time.

Second, partial function

A typical application that functions as a return value output is a partial function. The so-called partial function is the use of a function that creates a function that invokes another part-the parameter or variable that has been preset. Anyway, looking at the definition, I didn't understand what this stuff did. Let's take a look at the example first, the most typical example of a biased function is type judgment.

JavaScript objects have three properties: Prototype properties, class properties, extensibility. (Don't know the classmate to go back to the Rhino book Oh, page:138) The Class property is a string that is not directly available in JavaScript, but we can use Object.prototype.toString to get it indirectly. The function always returns the following form:

[object Class]

So we can write a series of istype functions. The code is as follows: For example, judging if it is not an array the most common practice is Object.prototype.toString.call ([+]) Its return value is a string "[Object array]", Determine if the string Object.prototype.toString.call (' IVan ') returns "[Object String]", and our code might be like this:

var isstring =function (obj) {return Object.prototype.toString.call (obj) = = =  "[object string] ";}; var isarray = function (obj) { return Object.prototype.toString.call (obj) = = =  "[object array] ";}; var isnumber = function (obj) { return Object.prototype.toString.call (obj) = = =  "[object number] ";    

Most of the code in these functions is repetitive, and the higher-order functions are now ornate:

var istype =function (type) {Returnfunction (obj) {return Object.prototype.toString.call (obj) = = =‘[Object' + type +‘] ";}; var isstring = Istype ( '  String " var IsArray = Istype ( ' array  "var isnumber = Istype ( '  Number "1, 2, 3])); //true         

So by specifying some parameters to return a new custom function, the form is the partial function.

SAN,currying (currying)

Currying is also called partial evaluation. A currying function will first accept some parameters, after accepting these parameters, the function will not evaluate immediately, but continue to return another function, the parameters just passed in the function formed in the closure of the saved up. Until the function is truly evaluated, all previously passed parameters are evaluated once.

var currying = function (fn) {    var args = [];         return function () {        if0) {            return fn.applay (this  , args);         Else {            = args.concat (arguments);             return Arguments.callee;     }}}

Let's say we take the one-month cost per day as an example:

varcurrying =function (FN) {varargs = []; returnfunction () {if(Arguments.length = = =0) {            returnFn.apply ( This, args); } Else{Array.prototype.push.apply (args, arguments); returnArguments.callee; }}}cost=function () {varsum =0;  for(vari =0, Len = arguments.length; i < Len; i++) {sum+=Arguments[i]; }        returnsum;}varCost =currying (cost) , cost ( -); Cost ( $); alert (Cost ())

Iv. Throttling of events

In some scenarios, some events may be triggered repeatedly, but event handlers do not need to be executed every time. For example, in the Window.resize event, complex logic calculations, if the user frequently change the browser size, complex calculations will have a serious impact on performance, and sometimes these logical calculations do not need to be triggered every time rezise, only a limited number of times to calculate. At this point we need to ignore some event requests based on the time period. Take a look at the following throttling functions:

function Throttle (FN, interval) {vardoing =false; returnfunction () {if(doing) {return; } doing=true; Fn.apply ( This, arguments); SetTimeout (function () {doing=false;  }, Interval); }}window.onresize=Throttle (function () {Console.log ('Execute');},  -);

By controlling function execution time, you can achieve a perfect balance between function execution times and functional requirements. Another event is MouseMove. If we bind the event to a DOM element, the event will be triggered repeatedly when the mouse moves over the element.

V. The end of the event

For some events that can be triggered frequently, we sometimes want to do a series of actions after the event ends. At this point we can use the higher order function to do the following:

function Debounce (FN, interval) {varTimer =NULL; function delay () {vartarget = This; varargs =arguments; returnsetTimeout (function () {fn.apply (target, args);  }, Interval); }  returnfunction () {if(timer) {cleartimeout (timer); } Timer= Delay.apply ( This, arguments); }};window.onresize=Throttle (function () {Console.log ('Resize End');},  -);

If the event is triggered during this process, the last event handle is cleared, and the execution time is re-bound.

JS Higher order function

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.