在JavaScript初始化期间“无法设置未定义的属性'x'”

时间:2014-11-13 08:14:29

标签: 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>

3 个答案:

答案 0 :(得分:0)

在分配事件监听器时,您正在丢失对象的上下文。基本上this内的新onmousemove(大部分时间)绑定到元素,触发了事件。解决这个问题有两种可能性:

使用bind()

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

使用匿名函数和指向旧this的指针:

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

答案 1 :(得分:0)

在活动内部,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 :(得分:-2)

更改

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

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