当前位置:网站首页>Understand JS high-order function and write a high-order function

Understand JS high-order function and write a high-order function

2022-06-25 05:05:00 I am Feng Feng Yi

If you are learning JavaScript, So you should have seen the term higher order function . Although it sounds complicated , But it's not hard . send JavaScript The reason for functional programming is that it accepts higher-order functions . Higher order functions are in JavaScript Widely used in . If you already use JavaScript Programmed for a while , You may have used them before you know it .

Misunderstanding of higher order function : Higher order functions do not mean that parameters have function parameters , Then the return value is the function of the function .

I understand it : Higher order functions refer to formal parameters with function parameters , And this higher-order function uses function parameters to do some things , Including processing some logic or encapsulating it into another function to return .

stay JS There are many higher-order functions in , Especially arrays
For example , You'll see .
Array.prototype.map

Let's first look at method calls

const arr = [1,2,3];
const res = arr.map(it=>it*it);
// res [1,4,9];

Another simple simulation map

Array.prototype.map = function (cb,_this) {
    
	if(!Array.isArray(this) || typeof cb !== 'function') {
    
		return
	}
	const map = [];
	const arr = this;
	for(let i = 0; i < arr.length; i ++) {
    
	 	map.push(cb.call(_this,arr[i],i,arr));
	}
	return map;
}

In this simulation Array.prototype.map The function of , We passed a function parameter , And use this function parameter to do some things , This map A function is a higher order function .

perhaps

We encapsulate a function and return a new function

const hof = function (func) {
    
	return function (...args) {
    
		 Here are some things to deal with 
		func.apply(this,args);
		 Encapsulating functions 
	}
}

there hof Function is also a higher-order function , It encapsulates the passed in function parameters , Enhanced the function .

Common anti shake at the front end , Throttling and coriolism are also classic examples of higher-order functions , Higher order functions can improve the readability of our code , It can also improve the extensibility of our code , You can encapsulate existing functions , Enhance its function .

原网站

版权声明
本文为[I am Feng Feng Yi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202210527410725.html