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



我有一个代码,在其中我使用"然后在构造函数中初始化它,然后当我尝试设置/访问该值时,我会得到以下错误

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)

您可以从下面的链接中进一步了解Javascript bind()。https://www.javascripttutorial.net/javascript-bind/

最新更新