This is the fourth day of my participation in Gwen Challenge
Follow up with the last one, which focuses on higher-order functions
What is a higher-order function?
- A function that takes a function as an argument or returns a function as output.
function foo(x){
return function(){
returnx; }}Copy the code
- Why do we have higher-order functions?
- Higher-order functions are much more flexible than ordinary functions. In addition to the usual sense of function call return, higher-order functions also form a way to receive the result of a subsequent transfer style, rather than a single return value form. The subsequent transfer style of programming shifts the business focus of functions from the return value to the callback function.
- High-order functions are widely used in JS, among which some array methods provided by ECMAScript5 are typical high-order functions, such as forEach(), map(), reduce(), reduceRight(), filter(), every(), some(), etc.
- The function is passed in as an argument
- The most common type of function passed as an argument is the callback function. For example, the callback function is used very frequently during asynchronous Ajax requests. Because asynchronous execution does not determine when the request will return, the callback function is passed in as an argument and executed when the request completes.
$.ajax({
url: 'ajaxUrl'.data: data,
success: function (res) { callback && callback(res.result.songs); }})Copy the code
- Function is output as the return value
- There are too many applications where functions are output as return values, and this is the idea of functional programming. We’ve already seen higher-order functions in the closure example.
- Remember when we go to judge data types, we are all through the Object. The prototype. ToString, between each data type just ‘[Object] XXX’ is not the same.
- Encapsulate a higher-order function to realize the judgment of different types of variables
function isType (type) {
return function (obj) {
return Object.prototype.toString.call(obj) === `[object ${type}] } } const isArray = isType('Array'); Const isString = isType('String'); Console. log(isArray([1, 2]); // true console.log(isString({}); // falseCopy the code