这个算是我在偶尔中发现的一个问题,因为最近都喜欢使用class
来写,所以这个里面的this
感觉乱飞,最近就因为一个绑定事件让我搞不懂,我这里就写了一个简单的demo来表示
html
<button onclick="add()">绑定事件</button>
<button onclick="removeEvent()">解绑事件</button>
<button id="button">点击</button>
js
class event {
constructor(prop) {
this.element = prop
}
handler() {
console.log(this);
}
add() {
this.element.addEventListener('click', this.handler.bind(this), false);
}
destroy() {
this.element.removeEventListener('click', this.handler, false);
}
};
const Event = new event(ele)
function add() {
Event.add();
}
function removeEvent() {
Event.destroy()
}
我在点击绑定事件按钮后点击最右边按钮会正确打印event
这个类,因为是改变了上下文,但是我点击解绑后再点击右边按钮还是会打印,说明我没有解绑成功,后面查资料就发现绑定和解绑都是只能使用函数(不能是匿名函数、或者直接function
)这种的。
add() {
this.element.addEventListener('click', this.handler);
}
如果这样写的话就没什么问题了,这样打印的就是
<button id="button">点击</button>
但是实际项目中我就是需要这个this
怎么办呢,也有个办法,虽然我们没法解绑,但是我们可以让他不执行呀
class event {
constructor(prop) {
this.element = prop
this.canClick;
}
handler() {
console.log(this);
}
add() {
this.canClick = true
this.element.addEventListener('click', this.handler.bind(this), false);
}
destroy() {
this.canClick = false
}
};
这样也能绕着圈子达到我们的目的,不过就是不那么好看!!