ts中this的处理

发布时间 2023-08-11 17:13:40作者: 蓓蕾心晴

ts函数中,直接使用this会报错:
"this" 隐式具有类型 "any",因为它没有类型注释。
应该以参数形式声明this,以防抖函数为例

 
function debounce(fn: Function, time: number) {
  let timer: number
  return function(this: object, ...args: any[]) {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
      clearTimeout(timer)
    }, time)
  }
}

编译后得到的js:

 
"use strict";
function debounce(fn, time) {
    let timer;
    return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(this, args);
            clearTimeout(timer);
        }, time);
    };

链接:https://www.jianshu.com/p/3ad19a3d2ce3