js防抖函数中的this和参数问题

这个问题是我在昨天的面试中被问到的问题,之前没有研究过,当时脑子一片混乱没有答出来,当时让我写防抖函数,我是这样写的:

function debounce (fn, delay) {
	let temp = null;
	return function () {
		if(temp) clearTimeout(temp);
		temp = setTimeout(() => {
			fn();
		}, delay);
	}
}

然后就被问到fn的this和参数怎么办,首先来解决一下this的问题,其实非常简单(面试的时候是真的脑子空白):

element.onclick = debounce(fn, delay);
function debounce (fn, delay) {
	lettemp = null;
	return function () {
		//因为这个函数是事件处理函数所以这个函数中的this就是element
		if(temp) clearTimeout(temp);
		temp = setTimeout(() => {
			fn.call(this); //你也可以用apply
		}, delay);
		//还可以这么写
		//temp = setTimeout(fn.bind(this), delay)
	}
}

下面来看参数怎么传进去:

//首先这样是肯定不行的
debounce(fn(1), delay)
//因为这样fn就直接执行了,那我想到了用bind
debounce(fn.bind(null, 1), delay)
//这样参数问题解决了,但是this又没有了

下面是我的解决方法(个人看法):

//假设我要传两个参数,既然fn里传不了那就在debounce里传
element.onclick = debounce (fn, delay, 1, 2);

//简单的举个fn的例子
function fn (e, num1, num2) {
	console.log(e, num1, num2);
}

function debounce (fn, delay, ...nums) {
	let temp = null;
	return function (e) {
		if(temp) clearTimeout(temp);
		temp = setTimeout(() => {
			//e是事件处理函数都有的一个参数,nums是个数组,在用call的时候需要解构一下
			fn.call(this, e, ...nums)
			//当然这里也可以用apply但是要麻烦很多因为nums是数组,但还有个e
		}, delay);
	}
}

以上就是我想到的处理方法,如果大家有更好的方法希望能够在评论下分享一下,如果我的这个方法有问题也欢迎指正。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值