測試一
測試代碼如下
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 事件監聽回調時,既不能使用匿名函數,也不能改變指定函數的上下文。