2014-11-13 4 views
0

마우스를 움직일 때. 콘솔 말해 : 정의되지 않은 'x'속성을 설정할 수 없습니다 ... 왜 이런 일이? 어떻게 객체 초기화 .... 그런 이벤트 리스너를 할당 할 때 당신은 개체의 컨텍스트를 잃어버린하는JavaScript 초기화 중 "정의되지 않은 x '속성을 설정할 수 없습니다."

<html> 
     <head> 
     </head> 
     <body> 
      <div id = "div1"> 
        <img id="omna" src="http://online1.map.bdimg.com/tile/?qt=tile&x=0&y=0&z=4&styles=pl&udt=20141102" width="256px" height="256px" unselectable="on" style="position:absolute;user-select:yes;-moz-user-select:yes;-webkit-user-select:;"/> 
      </div> 

      <script type="text/javascript"> 
       var kMapControl = { 

        mousemovepos : { 
         x:0, 
         y:0 
        }, 

        onmousemove : function (ev) { 
         ev = ev || event; 
         // here tell me:this.mousemovepos.x is not undefined 
         this.mousemovepos.x = ev.clientX; 
         this.mousemovepos.y = ev.clientY; 
        }, 
        init : function(){ 
         var div = document.getElementById("div1"); 
         div.addEventListener("mousemove", this.onmousemove, false); 
        } 

       }; 
       window.onload = function(){ 
        kMapControl.init(); 
       }; 

     </script> 
    </body> 
    </html> 
+1

'EV = EV || 이벤트;는 W3C 이벤트 모델을 지원하지 않는 브라우저에서만 필요합니다. 이러한 브라우저에는 * addEventListener *가 없으므로 할당에별로 중요하지 않습니다. – RobG

답변

0

. 기본적으로 onmousemove 안에있는 새로운 this은 (대부분의 경우) 이벤트를 트리거 한 요소에 바인딩됩니다.

사용 bind() : : 이벤트 내부

init : function(){ 
    var div = document.getElementById("div1"), 
     that = this; 
    div.addEventListener("mousemove", function(ev){ that.onmousemove(ev); }, false); 
} 
+0

필자는 후자를 선호한다.'.bind '를 호출하는 것보다 비용이 적게 들며, 핸들러 내부의'this '는 객체가 아닌 요소를 참조한다는 의미를 유지한다. – Alnitak

+0

@Alnitak : 정말요? jsperf를 가리킬 수 있습니까? (의심하지 마라. 내가 처음 들었을 때이다.) – Amadan

+0

@Amadan 내부적으로'.bind'는 전달 된 매개 변수에 바인드 된 클로저를 리턴함으로써 작동하고, 그 결과 함수는 'Function .prototype.apply'. 'this'를 통해 자신 만의 별칭을 만드는 것이 더 간단합니다. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind – Alnitak

0

, this 이벤트의 대상 :

init : function(){ 
    var div = document.getElementById("div1"); 
    div.addEventListener("mousemove", this.onmousemove.bind(this), false); 
} 

이전 this에 익명 함수와 포인터를 사용하여 그 해결을위한 두 가지 가능성이 있습니다 (this === ev.target). ev에는 mousemovepos이 없으므로 this.mousemoveposundefined입니다. undefined에는 x이 없으므로 오류가 발생합니다. 이 옵션을 사용합니다 :

onmousemove : function (ev) { 
    ev = ev || event; 
    // here tell me:this.mousemovepos.x is not undefined 
    this.mousemovepos.x = ev.clientX; 
    this.mousemovepos.y = ev.clientY; 
}.bind(this), 
-2

변경

mousemovepos : { 
     x:0, 
     y:0 
}, 

this.mousemovepos : { 
     x:0, 
     y:0 
}, 
+0

완전히 틀렸고 합법적 인 구문도 아닙니다. – Alnitak

+0

맞습니다. 잠자기로 가야합니다. 그것은 분명히 내 취침 시간이 지난 것입니다. – takinola

관련 문제