上面的类中的所有方法都可以正常工作。
但是当我使用addEventListener(Click)调用它们时,对象方法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()函数在没有addEventListener(Click)的情况下可以正常工作,//但是其他方法在任何地方都可以正常工作,所以open()有何不同?
//表[0] [0]是类单元的对象
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添加一个匿名函数,称为onclick
如果要在该函数内调用表,则应在表[0] [0]外部分配一个变量。
const tb = table[0][0];
canvas.addEventListener('click', function (event)
{
tb.open();
tb.squareTest(); //works fine here
}
)