[英]1 of the all object methods not working with eventHandler mouse click
如果调用它们,上面 class 中的所有方法都可以正常工作。
但是当我用 addEventListener(Click) 调用它们时,object 方法 open() 不起作用,但其他方法在这里也起作用。 请帮我找出我在哪里犯了错误?
class Cell {
constructor (x,y) {
this.x = x
this.y = y
this.w = cellWidth
this.h = cellHeight
this.opened = false
this.hasMine = true
}
squareTest () {
c.beginPath()
c.rect(100,100,100,100)
c.stroke()
}
cellBody () {
c.beginPath()
c.fillStyle = "rgba(0, 100, 100, 0.1)"
c.strokeStyle = "rgba(0, 100, 100, 1)"
c.rect (this.x, this.y, this.w, this.h)
c.fill()
c.stroke ()
if (this.opened === true) {
if (this.hasMine === true) {
c.beginPath();
c.ellipse(this.x + this.w/2, this.y + this.w/2, 10, 10, 15,0,Math.PI*2,false);
c.stroke()
}
}
}
open () {
if(this.opened == false) {this.opened = true}
}
}
}
// 我在这里删除了一些代码以使这篇文章简短。
// open() function 在没有 addEventListener(Click) 的情况下可以正常工作, // 但是其他方法在任何地方都可以正常工作,那么 open() 有什么不同?
//表[0][0]是Class Cell的object
table[0][0].open();
// works fine here
table[0][0].squareTest();
// works fine here
canvas.addEventListener ('click', function (event)
{
table[0][0].open(); // DOES NOT WORK HERE
table[0][0].squareTest(); //works fine here
console.log (table[1][1]); //works fine
}
)
table[0][0].open();
// works fine here
canvas.addEventListener 添加一个匿名的 function 被称为 onclick
如果你想在 function 内部调用它,你应该在外部为 table[0][0] 分配一个变量。
const tb = table[0][0];
canvas.addEventListener('click', function (event)
{
tb.open();
tb.squareTest();
}
);
这样,您将参考要在 onclick function 中使用的该表;
这是假设您有一个控制台错误,显示 table[0][0] 未定义。 是这样吗?
代码中没有错误....但是我没有得到所需的 output 因为还有另一个 function 没有用 open() 调用
感谢大家:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.