2017-03-18 67 views
0

有人可以向我解释为什么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

*函数被调用*:哪个函数?请显示产生你没有想到的结果的代码? – trincot

回答

0

当你调用油门创建一个新的封闭器,其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'只有在输出中出现一次。

+0

非常感谢你,包括你在内的链接帮了很多忙,尤其是例7.我对闭包知识的缺乏导致了我的困惑。再次感谢! –

相关问题