为什么每次调用此函数时都没有将值设置为空?

Why is the value not set to null each time this function is called?

有人可以向我解释为什么每次调用函数时 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);
        }
    };
};

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

function test() {
}

var myTest = test.throttle(100);

myTest();
myTest();

当您随后调用函数 myTest - 已返回 - 重复时,它将作用于 lastEventTimestamp[=35= 的同一个实例] 多变的。请注意,调用该函数不会执行赋值 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' 在输出中只出现一次。