为什么每次调用此函数时值都不设置为null?

时间:2017-03-18 19:44:15

标签: javascript throttling

有人可以向我解释为什么每次调用函数时lastEventTimestamp都不会重置为null吗?

Function.prototype.throttle = function (milliseconds, context) {
    var baseFunction = this,
        lastEventTimestamp = null,
        limit = milliseconds;

    return function () {
        var self = context || this,
            args = arguments,
            now = Date.now();

        if (!lastEventTimestamp || now - lastEventTimestamp >= limit) {
            lastEventTimestamp = now;
            baseFunction.apply(self, args);
        }
    };
};

1 个答案:

答案 0 :(得分:0)

当您调用 throttle 时,会创建一个新的闭包,其中 lastEventTimestamp 定义为null。内部函数有一个对该变量的引用,所以当返回该函数时,闭包仍然有一个对它的引用,并保持其状态:

function test() {
}

var myTest = test.throttle(100);

myTest();
myTest();

当您再次调用返回的函数 myTest 时,它将作用于该 lastEventTimestamp 变量的同一实例。请注意,调用该函数不会执行赋值lastEventTimestamp = null,而只执行该内部函数体中的代码。所以确实没有理由重置该变量。它在两次通话之间保持状态。这是power of closures in JavaScript

查看在此代码段中执行的console.log次调用:



Function.prototype.throttle = function (milliseconds, context) {
    console.log('initialising throttle');
    var baseFunction = this,
        lastEventTimestamp = null,
        limit = milliseconds;

    return function () {
        console.log('running throttle wrapper function');
        var self = context || this,
            args = arguments,
            now = Date.now();

        if (!lastEventTimestamp || now - lastEventTimestamp >= limit) {
            lastEventTimestamp = now;
            console.log('calling original function');
            baseFunction.apply(self, args);
        }
    };
};

function test() {
    console.log('running test');
}

var myTest = test.throttle(100);

myTest();
myTest(); // runs too soon, so test is not called.




请注意'running throttle wrapper function'仅在输出中出现一次。