Not a privileged user
Not a privileged user

Reputation: 963

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">
MOVE MOUSE ON ME
</div>

Any ideas ?

Upvotes: 3

Views: 342

Answers (1)

Tibrogargan
Tibrogargan

Reputation: 4603

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);
}

Upvotes: 7

Related Questions