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); }
Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .
An event listener is a procedure in JavaScript that waits for an event to occur. The simple example of an event is a user clicking the mouse or pressing a key on the keyboard.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With