Reputation: 963
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
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