JS-高阶函数

函数柯里化

定义:先接受一些参数并形成闭包,并返回另一个函数,用于接受剩余的参数。调用另一个函数,会将所有的参数加入计算得到结果。

本质:固定部分参数,创建偏函数,使得函数的通用性降低,适用性提升。

一种柯里化的方法:

var curry = function (fn) {
	// 相当于 arguments.slice(1) ,只不过arguments对象中没有 slice方法,所以只能通过call来使用
    var args = [].slice.call(arguments, 1);
    return function() {
    	//等价写法 var newArgs = [...args, ...arguments]
        var newArgs = args.concat([].slice.call(arguments));
        // 普通函数,this == window
        return fn.apply(this, newArgs);
    };
};

使用案例:

function add(a,b){
	return a + b;
}

let addCurry = curry(add, 1);
addCurry(3);  // 4

https://github.com/mqyqingfeng/Blog/issues/42

函数防抖和函数节流

函数防抖

定义:当一个动作连续触发时,只执行最后一次。
原理:让将要执行的函数使用 setTimeout 等待一段时间后再执行。

// 基本思想,对于重复的func,只对最后一次进行回调,其它的都在下一个func到来时清除
const debounce = (func, wait) =>{
	let timer=null;
	return () =>{
		if(timer){
			clearTimeout(timer);
		}
		timer = setTimeout(func, wait);
	}
}

函数节流

定义:限制函数在一定时间内只执行一次
原理:将正在执行的方法加入 setTimeout ,在方法的执行期间,后续加入的直接返回,不加入延时。

// 
const throttle = (func, wait) =>{
	let timer = null;
	return (() =>{
		if(timer){
			return; // 存在则直接返回
		}
		timer = setTimeout(() =>{
			func();
			// 等待当前执行完毕
			timer = null;
		}, wait);
	})
}

https://www.cnblogs.com/aurora-ql/p/13757733.html

惰性函数

定义:函数执行的分支只会在函数第一次调用的时候执行。在第一次调用过程中,函数会被合适分支覆盖,后续的都是使用分支函数。

本质:函数重写。使用新函数来替换原始函数。

// 使用闭包(此处为立即执行函数)实现惰性函数
let addEvent = (
	function(){
		if(type A){
			return function(type, element, func){
				operation A
			}
		}else if(type B){
			return function(type, element, func){
				operation B
			}
		}else{
			return function(type, element, func){
				operation C
			}
		}
})();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值