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

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

    The javascript built-in Function.prototype.bind() is intended for this purpose.
    For example:

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

    More on the bind method here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

    Other wise you have to pass a reference of the object someObj to the element and use that reference in the line:

    console.log(this.referenceToObject.prop); //this references the DOM element in an event.
    

提交回复
热议问题