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

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.

Leave a Comment