类的方法内部如果含有this,它默认指向类的实例。但是,必须非常小心,一旦单独使用该方法,很可能报错。今天就遇到这种情况(伪代码):
/**
* 添加 mousemove事件
*/
addMouseMove () {
document.getElementById('xxx').addEventListener('mousemove', this.regionBarMouseMove);
}
/**
* 移除 mousemove事件
*/
removeMouseMove () {
document.getElementById('xxx').removeEventListener('mousemove', this.regionBarMouseMove);
}
/**
* 事件函数
*/
regionBarMouseMove () {
if (this.targetElement) {
....
}
}
上述代码在执行时,this.targetElement 其实是找不到的,因为此时的this执行了当时的运行环境,在这里指向的window。
于是,我想到的bind()函数,把this.regionBarMouseMove 改成 this.regionBarMouseMove.bind(this),虽然这样可以正常运行了,但是removeMouseMove 事件失效了。
因为添加和移除事件函数 必须是内存中的同一个引用,而此时bind(this) 导致这两个函数指向不同的内存地址;
正确的姿势应该是在类的constructor 改变this指向
constructor (options: OptionsType) {
this.regionBarMouseMove = this.regionBarMouseMove.bind(this);
}