有人可以向我解释为什么每次调用函数时都不会将 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);
}
};
};
当您调用油门时,会创建一个新的闭包,其中lastEventTimestamp被定义为null
。内部函数有一个对那个变量的引用,所以当这个函数被返回时,闭包仍然有一个对它的引用,并保持它的状态:
function test() {
}
var myTest = test.throttle(100);
myTest();
myTest();
然后,当您重复调用函数myTest —— 返回的 —— 时,它将作用于lastEventTimestamp变量的同一个实例。请注意,调用该函数不会执行赋值lastEventTimestamp = null
,而只会执行该内部函数体中的代码。所以确实没有理由应该重置该变量。它在调用之间保持其状态。这就是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'
在输出中只出现一次。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句