ts中this的处理

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);
    };
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容