[转]prototype 源码解读 超强推荐第1/3页

2019-06-03 06:49:33丽君

261   
262  * 之所以这样做,是因为 setTimeout 默认总以 window 对象为当前对象,也就是说,   
263   
264  * 如果 registerCallback 方法定义如下的话:   
265   
266  *     registerCallback: function() {   
267   
268  *         setTimeout(this.onTimerEvent, this.frequency * 1000);   
269   
270  *     }   
271   
272  * 那么,this.onTimeoutEvent 方法执行失败,因为它无法   
273   
274  * 访问 this.currentlyExecuting 属性。   
275   
276  * 而使用了bind以后,该方法才能正确的找到this,   
277   
278  * 也就是PeriodicalExecuter的当前实例。   
279   
280  */   
281    
282 var PeriodicalExecuter = Class.create();    
283    
284 PeriodicalExecuter.prototype = {    
285    
286   initialize: function(callback, frequency) {    
287    
288     this.callback = callback;    
289    
290     this.frequency = frequency;    
291    
292     this.currentlyExecuting = false;    
293    
294    
295     this.registerCallback();    
296    
297   },    
298    
299    
300   registerCallback: function() {    
301    
302     setTimeout(this.onTimerEvent.bind(this), this.frequency * 1000);    
303    
304   },    
305    
306    
307   onTimerEvent: function() {    
308    
309     if (!this.currentlyExecuting) {    
310    
311       try {