簡體   English   中英

所有 object 方法中的 1 個方法不適用於 eventHandler 鼠標單擊

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM