gpt4 book ai didi

javascript - 不能使用这个在对象中使用函数

转载 作者:太空宇宙 更新时间:2023-11-03 22:34:45 24 4
gpt4 key购买 nike

下面是我在我的对象中添加事件监听器时的代码:

this.canvas.addEventListener('mousemove', function (e) {
var canv = document.getElementById("some");
myGameArea.x = (e.clientX - canv.getBoundingClientRect().left);//Look at canv
myGameArea.y = (e.clientY - canv.getBoundingClientRect().top);//Look at canv
});

它有效,但只有当我使用 getElementById 找到我的 Canvas 元素然后使用 canv 来满足我的需要时。但如果我这样做:

this.canvas.addEventListener('mousemove', function (e) {
var canv = document.getElementById("some");
myGameArea.x = (e.clientX - this.canvas.getBoundingClientRect().left);//Look at this.canvas
myGameArea.y = (e.clientY - this.canvas.getBoundingClientRect().top);//Look at this.canvas
});

然后 myGameArea 根本没有改变,我的调试器告诉我:“Uncaught TypeError: Cannot read property 'getBoundingClientRect' of undefined at HTMLCanvasElement ”。在这部分代码之前,我已经在我的对象中声明了 Canvas ,并且我将 this.canvas 用于许多其他功能。那么我的问题在哪里呢?

最佳答案

在回调闭包中,this 的上下文是 Canvas 元素本身。因此,您只需使用 this 来引用 Canvas 。

this.canvas.addEventListener('mousemove', function (e) {
myGameArea.x = (e.clientX - this.getBoundingClientRect().left);
myGameArea.y = (e.clientY - this.getBoundingClientRect().top);
});

关于javascript - 不能使用这个在对象中使用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47002602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com