在 javascript 中设置全局私有 class 属性 的值时出错

Error while setting the value of a global private class property in javascript

我有一个代码,其中我使用“#”声明了一个私有 class 成员,然后在构造函数中对其进行初始化,然后当我尝试设置/访问该值时,出现以下错误

Uncaught TypeError: Cannot read private member #mouse from an object whose class did not declare it
    at mouseDownEvent

其中 mouseDownEvent 是我尝试访问值的函数

代码示例:(参考EDIT代码)

class Testing
{
   #property;
   constructor()
   {
      this.#property = new Vector2();
   }

   mouseDownEvent()
   {
      this.#mouse.x = somevalue; <- error is here
   }
}

编辑

class Testing
{
   #mouse;
   constructor()
   {
      this.#mouse= new Vector2();
   }

   mouseDownEvent()
   {
      this.#mouse.x = somevalue; <- error is here
   }
}

由于您将 mouseDownEvent 函数传递给事件侦听器,因此 this 的值在实际调用时不会是此 Testing 实例。因此,在将它传递给事件处理程序时,您需要 将其绑定 到此实例,如下所示。

window.addEventListener("mousedown", mouseDownEvent.bind(this)(), false)

您可以从下方 link 进一步了解 Javascript bind()。 https://www.javascripttutorial.net/javascript-bind/