Javascript is your high-level function (advanced application), javascript high-level

Source: Internet
Author: User

Javascript is your high-level function (advanced application), javascript high-level

In common programming languages, function parameters can only be basic types or object references, and return values are only basic data types or object references. However, in Javascript, a function can be passed as a parameter or returned as a return value. A high-order function can take a function as a parameter or a function as a return value. These two situations have many application scenarios in actual development. This article is a summary of several application scenarios I encountered during my work and study.

Callback Function

Code reuse is one of the important criteria for measuring an application. By encapsulating the changed business logic in the callback function, the code reuse rate can be effectively improved. For example, the forEach method added to the array in ES5 traverses the array and calls the same function for each element.

array = {};array.forEach = function(arr, fn){  for (var i = 0, len = arr.length; i < len; i++) {    fn(arr[i], i, arr);  }}

The callback function focuses the business on the callback function, instead of repeatedly writing the traversal code every time.

 Partial function

A typical application that outputs functions as return values is partial functions. The so-called partial function refers to the usage of a function that creates a function that calls another part-a parameter or a preset function of a variable. I didn't understand what this stuff was doing. Let's take a look at the example first. The most typical example of partial functions is type judgment.

Javascript objects have three attributes: Prototype, class, and scalability. (If you don't know, you have to go back to the rhino book, page: 138) class attributes are a string, which is not directly provided in Javascript, but we can use Object. prototype. toString. This function always returns the following form:

[Object Class]

Therefore, we can compile 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 repeated. Then, the high-order functions are shown as follows:

isType = function(type) {  return function(obj) {    return Object.prototype.toString.call(obj) === "[object " + type + "]";  }}isString = isType('String');isNumber = isType('Number');isArray = isType('Array');

Therefore, the form of returning a new custom function by specifying some parameters is partial function.

Currying)

Currying is also called partial evaluation. A currying function first accepts some parameters. After accepting these parameters, the function does not evaluate them immediately, but returns another function, the parameters just passed in are saved in the closure formed by the function. When the function is actually required, all previously passed parameters will be used for value evaluation at one time.

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

Assume that we calculate the daily spending for one month 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 cost = currying(cost);cost(100);cost(200);alert(cost())

Event throttling

In some scenarios, some events may be repeatedly triggered, but the event processing function does not need to be executed every time. For example, in window. the resize event carries out complex logic computing. If the user frequently changes the browser size, complex computing will have a serious impact on the performance. Sometimes these logical computing tasks do not need to be triggered every time they are rezise, you only need to calculate a limited number of times. In this case, we need to ignore some event requests according to the time period. See the following throttling functions:

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 the 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 and move the mouse over the modified element, this event will be triggered again.

Event ended

For some events that can be triggered frequently, sometimes we want to perform a series of operations after the event ends. In this case, we can use the higher-order functions for the following processing:

 

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 an event is triggered during this process, the last event handle is cleared and the execution time is rebound.

References:

In-depth introduction to node

Javascript design patterns and development practices

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.