【问题标题】:Why is the value not set to null each time this function is called?为什么每次调用这个函数时值都没有设置为null?
【发布时间】:2017-03-18 19:44:14
【问题描述】:

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

【问题讨论】:

  • 调用了一个函数:哪个函数?请显示产生您意想不到的结果的代码?

标签: javascript throttling


【解决方案1】:

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

function test() {
}

var myTest = test.throttle(100);

myTest();
myTest();

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

查看在这个 sn-p 中执行了哪些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' 在输出中只出现一次。

【讨论】:

  • 非常感谢,您提供的链接帮助很大,尤其是示例 7。我对闭包的了解不足导致我感到困惑。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-16
  • 1970-01-01
  • 2020-05-10
  • 2016-11-29
  • 1970-01-01
  • 2019-06-28
相关资源
最近更新 更多