防抖中-----this指向的改变

137 阅读1分钟
   // 改变函数里的this指向;
    var boxEle = document.querySelector(".box");
    boxEle.onclick = debounce(function () {
        console.log(2, this);
        this.style.background = "blue";
    }, 2000);


    function debounce(fn, delay) {
        var timer = null;
        return function () {
            console.log(1, this);
            if (!timer) {
                fn && fn();
            }
            clearTimeout(timer);
            timer = setTimeout(function () {
                timer = null;
            }, delay)
        }
    }

image.png

修改this指向后

image.png