Accessing an object's property from an event listener call in Javascript

后端 未结 6 1507
借酒劲吻你
借酒劲吻你 2020-12-05 05:00

Below I am creating an object in Javascript. Within the constructor I am setting up an event listener. The problem is that when the event gets fired, this.prop cannot be fou

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 05:34

    First, you need to understand how 'this' works in JavaScript. 'this' keyword doesn't behave how it behaves in other languages like C# or JAVA. Read following post to understand more,

    What is the rationale for the behavior of the 'this' keyword in JavaScript?

    Once you understand that, as Matthew outlined in his code, you can save reference to 'this' and use that reference inside the mouseMoving function.

    Though overall, I will advise that you use a JavaScript framework (e.g. jQuery, YUI, MooTools) which will take care of these issues for you. E.g. In Internet Explorer, you use addEvent to attach event and not addEventListenr.

提交回复
热议问题