节流函数,可以有效减少页面的性能消耗和网络传输次数,提高用户的使用体验,在页面滚动和按钮重复点击中常常使用。以下为一常见的节流函数:
function throttle(fn, wait) {
let timer;
return function() {
let context = this,
args = arguments;
if (!timer) {
timer = setTimeout(function() {
fn.apply(context, args);//此处也可用call函数
timer = null;
}, wait);
}
};
}
let context = this获取上下文,this
的含义取决于你如何调用返回的函数。this
在JavaScript中是一个动态的值,它基于函数的调用方式。
-
作为普通函数调用:
如果你直接调用这个返回的函数,比如var throttledFn = throttle(myFunction, 500); throttledFn();
,那么在这个新函数的内部,this
将指向全局对象(在浏览器中是window
),除非在严格模式('use strict'
)下,此时this
将是undefined
。 -
作为对象的方法调用:
如果你将这个返回的函数赋值给某个对象的属性,并通过这个对象来调用它,比如obj.throttledMethod = throttle(myMethod, 500); obj.throttledMethod();
那么在这个新函数的内部,this
将指向obj
。 -
使用
.call()
,.apply()
, 或.bind()
调用:
你也可以使用这些方法来显式地设置this
的值。例如:let context = someObject; let throttledFn = throttle(myFunction, 500); throttledFn.call(context); // 在这里,this将指向someObject
其中args = arguments为函数调用时传入的参数; call和apply函数都是用来改变this指向,唯一区别就是参数不同。
function myFunction(a,b,c) {
console.log(a,b,c);
}
let throttledFunction = throttle(myFunction, 500);
throttle中使用apply方法
throttledFunction(1,2,3);//打印1,2,3
而throttle中使用call方法
throttledFunction(1,2,3);//打印[1,2,3],undefined,undefined