Javascript is your higher-order function (advanced application) _javascript techniques

Source: Internet
Author: User

In a normal programming language, the parameter of a function can only be a base type or an object reference, and the return value is only a basic data type or an object reference. In JavaScript, however, a function as a first-class citizen can be passed as a parameter or returned as a return value. A higher order function is a function that can take a function as a parameter, or a function as a return value. These two situations have many application scenes in the actual development, this article is the summary which I encountered in the work study several application scenarios.

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 package in the callback function. For example, the ES5 method, which iterates through arrays and calls the same function for each element, is added to an array.

Array = {};
Array.foreach = function (arr, fn) {
  for (var i = 0, len = arr.length; i < Len; i++) {
    fn (arr[i), I, arr);
  }
}

Focus the business focus on the callback function through the callback function without having to repeatedly write the traversal code every time.

 Partial function

A typical application that uses a function as the output of a return value is a partial function. A partial function is the use of a function that creates a function that calls another part of a parameter or variable that has already been preset. Anyway, look at the definition. I don't understand what this stuff does. Let's look at the example first, the most typical example of a partial function is type judgment.

JavaScript objects all have three properties: Stereotype Properties, class attributes, extensibility. (Don't know the classmate to go back to the Rhino book Oh, page:138) class attribute is a string that is not provided directly 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:

isstring = function (obj) {return
  Object.prototype.toString.call (obj) = = "[Object String]";
}
Isnumber = function (obj) {return
  Object.prototype.toString.call (obj) = = "[Object number]";
}
IsArray = function (obj) {return
  Object.prototype.toString.call (obj) = = "[Object Array]";
}

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

Istype = function (type) {return
  function (obj) {return
    Object.prototype.toString.call (obj) = = "[Object] + ty PE + "]";
  }
}

isstring = Istype (' String ');
Isnumber = Istype (' number ');
IsArray = Istype (' Array ');

So the form of returning a new custom function by specifying a partial parameter is a partial function.

Currying (Corrie)

Currying is also called partial evaluation. A currying function takes some arguments first, and after accepting the arguments, the function is not evaluated immediately, but instead continues to return another function, and the arguments just passed in are saved in the closure of the function formation. When a function is actually evaluated, all parameters passed in before are evaluated at once.

var currying = function (fn) {
  var args = [];
  
  return function () {
    if (arguments.length = 0) {return
      fn.applay (this, args);
    } else {
      args = Args.conca T (arguments);
      return arguments.callee;
    }
  }

Suppose we take the one-month-per-day spending as an example:

var currying = function (fn) {
debugger;
  var args = [];
  
  return function () {
    if (arguments.length = 0) {return
      fn.apply (this, args);
    } else {
      Array.prototype.push.apply (args, arguments);
      return arguments.callee;
    }
  }

Cost = function () {
  var sum = 0;
  for (var i = 0, len = arguments.length i < len; i++) {
    sum + + arguments[i];
  }
  
  return sum;
}
var = currying (cost);

Cost (m);
Cost (in);
Alert (Cost ())

Event throttling

In some scenarios, some events may be triggered repeatedly, but the event handler function does not need to be executed every time. For example, in the Window.resize event for complex logical calculations, if the user frequently changes the size of the browser, complex computing can have a serious impact on performance, sometimes these logical calculations do not need to be triggered every time rezise, only a limited number of calculations can be. Then we need to ignore some event requests based on the time period. Consider the following throttle function:

Function Throttle (FN, interval) {
   var doing = false;

   return function () {
    if (doing) {return
     ;
    }
    doing = true;
    Fn.apply (this, arguments);
    settimeout (function () {
     doing = false;
    }, Interval);
   }
  
  Window.onresize = throttle (function () {
    console.log (' execute ');
  }, 500);

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

End of event

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

Function Debounce (FN, interval) {
  var timer = null;

 function delay () {
  var target = this;
  var args = arguments;
  Return settimeout (function () {
   fn.apply (target, args);
  }, Interval);
 }

 return function () {
  if (timer) {
   cleartimeout (timer);
  }

  Timer = delay.apply (this, arguments);
 }
;
Window.onresize = throttle (function () {
  console.log (' resize end ');
}, 500);

If the event is triggered during this process, clears the last event handle and rebind the execution time.

Resources:

"In simple and Simple node"

JavaScript design pattern and development practice

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.