今天写了一个throttle函数,在对传进去的函数进行封装的时候,纠结了一会,要不要绑定this? 答案是最好要。
假设我没有绑定this,可以看到myFunc函数的this指向的是window.
javascript
function throttle (fn, gap) {
let previous = 0;
return function(...args) {
const now = Date.now();
if (now - previous > gap) {
fn(...args);// 没有绑定this
previous = now;
}
}
}
const obj = { name: 'Alice' };
const obj2 = { name: 'Bob' };
function myFunc (a, b) {
debugger
console.log(this.name + ' says ' + a + ' ' + b);
}
const throttledFunc = throttle(myFunc, 5000);
throttledFunc.call(obj2, 'Hello', 'world');// undefined says Hello world
如果我想灵活绑定不同的this对象给myFunc函数就做不到,我们在throttle函数中绑定this,再看看
ini
function throttle (fn, gap) {
let previous = 0;
return function(...args) {
const now = Date.now();
if (now - previous > gap) {
fn.apply(this,args);// 绑定了this
previous = now;
}
}
}
const obj = { name: 'Alice' };
const obj2 = { name: 'Bob' };
function myFunc (a, b) {
debugger
console.log(this.name + ' says ' + a + ' ' + b);
}
const throttledFunc = throttle(myFunc, 5000);
throttledFunc.call(obj2, 'Hello', 'world');
这时候this指向了obj2对象,而且我们还能灵活改成其他对象
所以在throttle函数中,绑定this是有必要的,相当于是this对象的转发层,转发给throttle包裹的函数,可以用不上this,但是转发的功能要保留。