EventListener中的handleEvent

在研究代码时发现类似这样一段代码:

 1 function TEST() {}
 2 
 3 TEST.prototype = {
 4   init:function() {
 5     window.addEventListener('mousedown',this);
 6   },
 7   handleEvent:function(e) {
 8     alert('mousedown');
 9   }
10 };
11 
12 new TEST().init();

最初对于第5行不是很理解,为什么可以传一个this作为参数,并且最终还成功地执行了alert方法,毕竟this是一个构造函数而非具体的方法。

后来查阅了相关文档,发现关键之处在于handleEvent这个函数,该函数原本就存在于《DOM2级事件规范》中:

// Introduced in DOM Level 2:
interface EventListener {
  void handleEvent(in Event evt);
};

这个接口规定了handleEvent应该如何实现。也就是说,在使用addEventListener时,第二个参数可以传入一个对象、函数或者像上面的构造函数,在执行该语句时,它会自动

寻找参数中的handleEvent方法并执行,并且this指向这个参数,不会受addEventListener的影响。

目前如何更好地运用这一方式还在探索中。

参考资料:https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventListener

原文地址:https://www.cnblogs.com/undefined000/p/handleEvent.html