3

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 ?

1 Answer 1

7

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

You should mark it as a duplicate, there are already plenty of questions exactly like this
wtf, i hate javascript now. Thanks!
@Notaprivilegeduser Don't hate. The way JavaScript binds (or doesn't bind) functions is actually really powerful once you get a handle on it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.