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

后端 未结 6 1497
借酒劲吻你
借酒劲吻你 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:33

    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.

提交回复
热议问题