簡體   English   中英

無法在實例內讀取Object(undefined?)上的屬性

[英]Cannot read property on Object (undefined?) inside instance

當我嘗試從事件函數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處理程序時,該函數不會綁定到MyClass實例。 您可以通過顯式綁定它來解決此問題:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM