js面向对象函数之间如何调用?

function Dumplings(DOMselect){
    this.ele=DOMselect;
  }
  Dumplings.prototype.move=function(){
    var _this=this;
    var isdrag=false;   
    var tx,ty,x,y;
    this.ele.addEventListener('touchstart',selectmouse);//如何调用selectmouse
    console.log("move");
  }
  Dumplings.prototype.selectmouse=function(e){
    console.log("move");
    isdrag = true;
    tx = parseInt(this.style.left+0);   
    ty = parseInt(this.style.top+0);
    x = e.touches[0].pageX;
    y = e.touches[0].pageY;
    this.addEventListener('touchmove',movemouse);//如何调用movemouse方法?
    this.addEventListener('touchend',function(){  
      sdrag = false; 
      this.removeEventListener('touchmove',movemouse); //如何调用movemouse方法?  
    }); 
  }
  Dumplings.prototype.movemouse=function(e){
    if (isdrag){   
     var n = tx + e.touches[0].pageX - x;
     var m = ty + e.touches[0].pageY - y;
     if (n >= winW - 100) n = winW - 100;
     if (n <= 0) n = 0;
     if (m >= winH - 100) m = winH - 100;
     if (m <= 0) m = 0;
     this.style.left = n+"px";
     this.style.top  = m+"px";
     return false;   
    } 
  }

上面的代码,如何调用prototype之间的函数,this已经改变。。

阅读 3.9k
3 个回答

对于 "touchstart" 可以直接把 this.selectmouse.bind(this) 作为事件处理函数。但是对于需要 remove 的 movemouse 就不能直接这样干了,每次 bind 都会产生新的函数对象,所以需要预先保留下来后面才能 remove。

Dumplings.prototype.selectmouse = function(e) {
    console.log("move");
    isdrag = true;
    tx = parseInt(this.style.left + 0);
    ty = parseInt(this.style.top + 0);
    x = e.touches[0].pageX;
    y = e.touches[0].pageY;
    
    // ----------------------------
    var _this = this;
    // 把需要 remove 的事件函数预告保留下来
    this._lastMoveEvent = this.movemouse.bind(this);
    this.addEventListener("touchmove", this.movemouse.bind(this));
    this.addEventListener("touchend", function() {
        sdrag = false;
        if (_this._lastMoveEvent) {
            // remove 这个 listener,记得把 _lastMoveEvent 也清了
            _this.removeEventListener("touchmove", _this._lastMoveEvent);
            _this._lastMoveEvent = null;
        }
    });
};

谢邀。
在原型里面直接用this

this.ele.addEventListener('touchmove', this.movemouse);
// 顺带一提,你后面有很多`this.addEventListener`等引用,肯定会报错的,你这儿应该是`this.ele.addEventListener`

然后你需要实例化

var dumplings = new Dumplings(document.body);
dumplings.move();

Function.prototype.bind即可

比如this.ele.addEventListener('touchstart', this.selectmouse.bind(this));


定义在Dumplings.prototype里的函数如果作为Dumplings实例的方法调用,其this指针会指向Dumpling实例。
但作为参数传递给其他函数(比如addEventListener)时其this指针会被重置,由addEventListener控制。

你需要在prototype里的函数里调用其它同级的函数,this就应当指向Dumplings实例,用this.ele来绑定事件和访问事件的对象,这样才能通过this来访问其他同级对象。为防止addEventListener改变this的指向,需要用bind固定下来。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题