javascript - js面向对象函数之间如何调用?
本文介绍了javascript - 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已经改变。。
解决方案
对于 "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;
}
});
};
这篇关于javascript - js面向对象函数之间如何调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文