Not a privileged user Not a privileged user - 1 year ago 106
Javascript Question

Cannot read property on Object (undefined?) inside instance

When i try to access the object this.guy from the event function onMouveMove i get the following error:

"Uncaught TypeError: Cannot read property 'prop1' of undefined"

When i inspect with Chrome's Devtool, the value exist and is there, it just doesn't recognize inside the "onMouseMove" function.

MyClass = function(some_html_element){
this.guy = {"prop1":[]};
some_html_element.onmousemove = this.onMouseMove;

MyClass.prototype.onMouseMove = function(evt){
if(!this.guy.prop1){ //<- here's the error
alert("no error");

a = new MyClass(document.querySelector("#example"))

<div id="example">

Any ideas ?

Answer Source

When you set the onMouseMove handler for some_html_element the function is not bound to your MyClass instance. You can fix this by explicitly binding it:

MyClass = function(some_html_element){
  this.guy = {"prop1":[]};
  some_html_element.onmousemove = this.onMouseMove.bind(this);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download