当我尝试从事件函数 onMouveMove 访问对象 this.guy 时,出现以下错误:
"Uncaught TypeError: Cannot read property 'prop1' of undefined"
当我使用 Chrome 的 Devtool 检查时,该值存在并且存在,只是在“onMouseMove”函数内部无法识别。
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>
有什么想法吗?
最佳答案
当您为 some_html_element 设置 onMouseMove 处理程序时,该函数未绑定(bind)到您的 MyClass 实例。您可以通过显式绑定(bind)来解决此问题:
MyClass = function(some_html_element){
this.guy = {"prop1":[]};
some_html_element.onmousemove = this.onMouseMove.bind(this);
}
关于javascript - 无法读取实例内对象(未定义?)的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40517904/