如何链接addEventListener?

Joe*_*dee 3 javascript addeventlistener

我有以下代码:

document.querySelector('.mySelector').addEventListener("mouseover", function() {
    this.parentNode.parentNode.classList.add("over");
});
document.querySelector('.mySelector').addEventListener("mouseout", function(){
    this.parentNode.parentNode.classList.remove("over");
});
Run Code Online (Sandbox Code Playgroud)

鉴于这两个事件在同一个目标上,有没有办法addEventListener将这两个方法链接起来呢?:

document.querySelector('.mySelector').addEventListener("mouseover", function() {
    this.parentNode.parentNode.classList.add("over");
}).addEventListener("mouseout", function(){
    this.parentNode.parentNode.classList.remove("over");
});
Run Code Online (Sandbox Code Playgroud)

这样做会产生错误:

未捕获的TypeError:无法读取未定义的属性"addEventListener"

idm*_*ean 7

链接addEventListener是不可能的,因为该方法不返回任何东西(它确实返回undefined).该规范规定了它:

 interface EventTarget {
  void               addEventListener(in DOMString type, 
                                      in EventListener listener, 
                                      in boolean useCapture);
Run Code Online (Sandbox Code Playgroud)

当然,您可以addEventListener使用自己的实现替换:

// Enhance the "addEventListener" method
EventTarget.prototype.addEventListener = (addEventListener => (...args) => {
  addEventListener.apply(this, args)
  return this
})(EventTarget.prototype.addEventListener)


// chained events binding
window
  .addEventListener('mouseup'  , e => console.log(e.type))
  .addEventListener('mousedown', e => console.log(e.type))
Run Code Online (Sandbox Code Playgroud)

但是,内置原型的混乱是经常被建议的,因为它可能会产生不必要的副作用.