es6的class中函数之间调用报错?

今天写一个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 !

发布了62 篇原创文章 · 获赞 9 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_37026254/article/details/89281984