Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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);   } 
like image 546
Ronald Avatar asked Jul 04 '09 04:07

Ronald


People also ask

How do you access the properties of an object with a variable?

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] .

What does an event listener to JavaScript?

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.


1 Answers

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.

like image 92
Matthew Crumley Avatar answered Sep 28 '22 08:09

Matthew Crumley