Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

防抖函数的this修正方式不正确 #3

Open
txy920 opened this issue Apr 24, 2022 · 1 comment
Open

防抖函数的this修正方式不正确 #3

txy920 opened this issue Apr 24, 2022 · 1 comment

Comments

@txy920
Copy link

txy920 commented Apr 24, 2022

原文写法:

function debounce(fn, delay) {
    //记录上一次的延时器
    var timer = null;
    return function () {
       //清除上一次的演示器
        clearTimeout(timer);
        //重新设置新的延时器
        timer = setTimeout(function(){
            //修正this指向问题,!!setTimeout在这里改变了this的指向,指向了window!
            fn.apply(this);
        }, delay); 
    }
}

正确写法:

function debounce(fn, delay) {
    //记录上一次的延时器
    var timer = null;
    return function () {
       //清除上一次的演示器
        clearTimeout(timer);
       // 保存执行上下文的this对象,例如:事件触发对象
        var that = this; 
        //重新设置新的延时器,使用箭头函数可能更好
        timer = setTimeout(function(){
            fn.apply(that);
        }, delay); 
    }
}
@penghei
Copy link

penghei commented May 8, 2022

原文写法:

function debounce(fn, delay) {
    //记录上一次的延时器
    var timer = null;
    return function () {
       //清除上一次的演示器
        clearTimeout(timer);
        //重新设置新的延时器
        timer = setTimeout(function(){
            //修正this指向问题,!!setTimeout在这里改变了this的指向,指向了window!
            fn.apply(this);
        }, delay); 
    }
}

正确写法:

function debounce(fn, delay) {
    //记录上一次的延时器
    var timer = null;
    return function () {
       //清除上一次的演示器
        clearTimeout(timer);
       // 保存执行上下文的this对象,例如:事件触发对象
        var that = this; 
        //重新设置新的延时器,使用箭头函数可能更好
        timer = setTimeout(function(){
            fn.apply(that);
        }, delay); 
    }
}

setTimeout里边直接用箭头函数也可以

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants