从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,但是转发的功能要保留。

相关推荐
irving同学46238几秒前
Drizzle ORM + PostgreSQL + Hono 学习笔记
前端·后端
明豆几秒前
HTTPS / TLS 1.3 深度解析 — Web 安全传输协议生产实战
前端·安全·https
Linsk1 分钟前
Rollup 官方插件 @rollup/plugin-inject 详解
前端·rollup.js·前端工程化
2601_958492552 分钟前
Performance Audit of Paper Boats Racing - HTML5 Racing Game
前端·html·html5
浮生望3 分钟前
《JavaScript语言精粹》第3章:对象——JS世界的基石
javascript
irving同学462384 分钟前
TypeScript 后端入门全景:Hono + Zod + Drizzle + PostgreSQL
前端·后端
一致性4 分钟前
项目总结:桌宠(Desktop Pet)
前端
学掌门12 分钟前
JavaScript:为什么命名参数比位置参数更好
开发语言·javascript·ecmascript
JoneBB12 分钟前
ABAP上传EXCEL模板并将内表内容存到两个sheet中
java·前端·数据库
usdoc文档预览26 分钟前
国产化踩坑:Vue3 / React / 小程序如何免插件实现 OFD 及复杂 Office 文档同屏预览
前端·javascript·react.js·小程序·pdf·word·office文件在线预览