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

后端 未结 6 1508
借酒劲吻你
借酒劲吻你 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条回答
  •  醉话见心
    2020-12-05 05:41

    You could use a variable named 'me', to avoid conflict with the global JavaScript variable 'self':

    function someObj() {
      var me = this;
      this.prop = 33;
    
      this.mouseMoving = function() {
        alert(me.prop);
      }
    
      document.getElementById("someDiv").addEventListener('mousemove', this.mouseMoving, true);
    }
    

提交回复
热议问题