Javascript”;onmousemove”;事件无法与类一起使用
Javascript "onmousemove" event not working with classes
我真的不知道如何在标题中表达这一点,但我正在尝试创建一个包含所有事件函数的类,但我遇到了奇怪的问题。
以下是该问题的一些模拟代码。
class Mouse{
constructor(){
this.x = 0;
this.y = 0;
}
}
class MainClass{
constructor(){
this.mouse = new Mouse();
}
updateMouse(event){
this.mouse.x = event.clientX;
this.mouse.y = event.clientY;
}
}
var mouse;
var main;
window.onload = function(){
main = new MainClass();
document.onmousemove = main.updateMouse;
}
我遇到的主要问题是,当我运行它时,它会返回错误"无法设置未定义的属性'x'",这很奇怪,因为当我遍历程序main.mouse.x时,直到document.onmousemove行。
如果我将updateMouse()函数移到Mouse类中,并改为执行以下操作:
mouse = new Mouse();
document.onmousemove = mouse.updateMouse();
然后它就工作了,但是在我试图编写的ACTUAL程序中,updateMouse()方法需要调用MainClass中的其他方法,所以我不能这样做。
您必须使用
window.onload = function(){
main = new MainClass();
document.onmousemove = main.updateMouse.bind(main); // bound function
};
试试看。如果不绑定函数,它会将"this"视为自身(文档对象)。
相关文章:
- 转义符不能与innerHTML一起使用
- 高亮显示与数组字符串一起使用时文本插件中断
- setTimeout可以与闭包内的函数一起使用吗
- 将依赖外部库的UMD模块与browserfy捆绑在一起
- Highcharts colorsByPoint与系列中的线性渐变一起使用时不起作用
- 如何将js库与typescript一起使用
- 将webpack和babel与父项目目录中的文件一起使用
- 将 Drag&Drop 与 jsTree 和 DataTables 一起使用
- Javascript-如何让脚本与Ajax请求的数据一起运行
- 将两个ext.TabPanels滚动到一起
- 将jQuery UI Timepicker Addon与React一起使用
- 什么是curl以及如何将其与nodejs一起使用
- Javascript”;onmousemove”;事件无法与类一起使用
- 将require('..')与变量一起使用与在webpack中使用字符串相比
- 如何在php中创建一个函数,该函数与文本区域一起工作,通过输入类似[color:red]的内容来打印具有等效颜色的文本
- 三角库可以与firefox一起使用,但不能在Chrome中使用
- 为什么不't我的ruby代码与javascript文件一起插入
- 通过jQueryAjax一起发布Array和Form数据时出现问题
- 如何将eventListeners与Angularjs+Electron一起使用
- 将FormParams与Jersey和jQuery一起使用