今天写一个demo 发现class 类中的函数互相调用报错 is not a function
- 代码如下:
class Map{
constructor(_wid){
this.cav= document.getElementById('canvas'); // 一个canvas
}
mousemove(e){
e = e || window.event;
e.preventDefault();
this.writeMth(); // 此处报错`this.writeMth() is not a function`
}
writeMth(){
console.log('鼠标移动了')
}
}
let maps = new Map();
maps.cav.onmousemove = maps.mousemove;
- 检查发现将调用函数的方法改为
maps.writeMth()
即可正常显示
mousemove(e){
e = e || window.event;
e.preventDefault();
if(this.isMouseDown){
maps.writeMth(); // 此处报错`this.writeMth() is not a function`
}
}
我猜测应该是函数调用时候 this
的指向已经发生改变
- 打印验证
this
值
mousemove(e){
e = e || window.event;
e.preventDefault();
console.log(this);
if(this.isMouseDown){
maps.writeMth();
}
}
- 果然
this
的指向this
的指向已经发生改变
问题来了,怎么能在函数中用 maps.writeMth()
的方式调用?stupid !
所以是在函数调用方法上出了问题
这里我们使用箭头函数调用
maps.cav.onmousemove =() => {
maps.mousemove();
};
ok !