首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Debounce函数无意义的行

Debounce函数无意义的行
EN

Stack Overflow用户
提问于 2019-08-02 22:15:03
回答 1查看 57关注 0票数 1

我有一个取自web的debounce函数。

代码语言:javascript
复制
function debounce(f, ms) {
    let timer = null;

    return function(...args) {
        const onComplete = () => {
            f.apply(this, args);
            timer = null;
        }

        if (timer) {
            clearTimeout(timer);
        }

        timer = setTimeout(onComplete, ms);
    }   

}

我们到底为什么需要这一行f.aply(this, args),如果我们把这一行改为f(args),结果就会一样。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-02 22:22:50

如果在不使用this的情况下调用去抖动函数

代码语言:javascript
复制
let deb = debounce(...);
deb()

这没什么区别。

如果使用this (通过bind/call/apply)调用它,则需要apply行才能将this正确地传递给源函数:

代码语言:javascript
复制
"use strict";

function debounce(f, ms) {
    let timer = null;

    return function(...args) {
        const onComplete = () => {
            console.log('with apply:')
            f.apply(this, args);
            console.log('without apply:')
            f(...args)
            timer = null;
        }

        if (timer) {
            clearTimeout(timer);
        }

        timer = setTimeout(onComplete, ms);
    }   

}

let x = {y: 1};
let deb = debounce(function() { console.log(this)}, 3);
deb.apply(x)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57328251

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档