记一次使用 removeEventListener 移除事件监听失败的经历

测试一

测试代码如下

var Test = function() {
  this.element = document.body;
  this.handler = function() {
    console.log(this);
  };
  this.element.addEventListener('click', this.handler.bind(this), false);
  this.destroy = function() {
    this.element.removeEventListener('click', this.handler, false);
  };
};
var test = new Test();

但是,测试结果发现,调用 test.destroy() 后,点击依旧有效。明明按照以前看的文档说的,add 和 remove 的时候是同一个函数啊。

测试二

于是,又调整了一下代码。

var Test = function() {
  this.element = document.body;
  this.handler = function() {
    console.log(this);
  };
  this.element.addEventListener('click', this.handler, false);
  this.destroy = function() {
    this.element.removeEventListener('click', this.handler, false);
  };
};

去掉了 add 时的 bind,再测试发现点击不响应了。

结论

经过测试,add 和 remove 事件监听回调时,既不能使用匿名函数,也不能改变指定函数的上下文。

原文地址:https://www.cnblogs.com/xiaoyucoding/p/8516407.html