Search code examples
javascripteventsevent-handlingdom-events

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


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 found, and undefined prints out. How do I solve this?

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

Solution

  • When the event handler gets called, "this" no longer references the "someObj" object. You need to capture "this" into a local variable that the mouseMoving function will capture.

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

    I'm assuming "someObj is a constructor, i.e. intended to be called with as new someObj(), otherwise "this" will be the global scope.

    The "this" keyword can be confusing in JavaScript, because it doesn't work the same way as in other languages. The key thing to remember is that it is bound to the calling object when the function is called, not when the function is created.