节流函数在2种方法名写法中的影响

65 阅读1分钟

场景: 点击事件进行函数节流,一秒内只触发一次点击事件,防止暴力点击。

methods: {
    test: throttle(function(){     //es5写法
        console.log('执行了')
    }, 1000),
    test() {                       //es6写法
        throttle(function(){
            console.log('执行了')
        }, 1000)
    }
}
// utils/utils.js  
export function throttle(fn, wait = 200) {
    let last,timer,now;
    return function() {
        now = Date.now();
        if(last && now - last < wait){
            clearTimeout(timer);
            timer = setTimeout(function(){
                last = now;
                fn.call(this, ...arguments);
            }, wait)
        }else {
            last = now;
            fn.call(this, ...arguments);
        }
    }
}

这里vue中的test方法用es6的写法就无法执行节流函数,es5的写法可以。虽然写法上无区别,但是效果却不同,下面es6的写法每次点击都创建了一个test方法,而不是每次点击都在同一个节流函数上执行。