无法在实例

时间:2016-11-09 23:47:19

标签: javascript

当我尝试从事件函数 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"))
&#13;
<div id="example">
MOVE MOUSE ON ME
</div>
&#13;
&#13;
&#13;

有什么想法吗?

1 个答案:

答案 0 :(得分:7)

为some_html_element设置onMouseMove处理程序时,该函数未绑定到MyClass实例。您可以通过显式绑定它来解决此问题:

MyClass = function(some_html_element){
  this.guy = {"prop1":[]};
  some_html_element.onmousemove = this.onMouseMove.bind(this);
}
相关问题