从throttle函数看绑定this指向的必要性

今天写了一个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,但是转发的功能要保留。

相关推荐
\xin3 小时前
pikachu自编exp,xss反射性get,post,存储型xss,dom,dom-x
前端·javascript·xss
是烟花哈7 小时前
【前端】React框架学习
前端·学习·react.js
qq4356947018 小时前
JavaWeb08
前端
2401_878454539 小时前
html和css的复习(1)
前端·css·html
@PHARAOH9 小时前
WHAT - git worktree 概念
前端·git
IT_陈寒10 小时前
我竟然被JavaScript的隐式类型转换坑了三天!
前端·人工智能·后端
我亚索贼六丶10 小时前
二十六. AI基础概念之如何更好的使用AI
前端
小码哥_常10 小时前
安卓启动页Logo适配秘籍:告别“奇形怪状”的展示
前端
我亚索贼六丶10 小时前
二十五.Electron 初体验与进阶
前端
当时只道寻常10 小时前
像使用 Redis 一样操作 LocalStorage
前端·前端工程化