js中可以改变方法作用域和参数的方式有三种,apply,call,bind.
apply 和call类似第一个参数是方法的作用域,其它参数是方法的参数。不同的是apply的其它参数是个数组,数组的个数为参数的个数,call除开第一个参数其它参数方法参数,例子如下
function method() {console.log(this, arguments)
}
var a = 1
var b = 2, c = 3, d = 4
method.call(a, b, c, d)// 打印 [Number: 1] { '0': 2, '1': 3, '2': 4 }
method.apply(a, [b, c, d])// 同上 [Number: 1] { '0': 2, '1': 3, '2': 4 }
bind 和call参数传递方式一致,唯一区别是bind不会立即执行,只会更改作用域和方法参数,到真正执行方法时才会执行。
var t = method.bind(a, b)t()// [Number: 1] { '0': 2 }
t = t.bind(null, c)
t()// [Number: 1] { '0': 2, '1': 3 }
t = t.bind(null, d)
t() // [Number: 1] { '0': 2, '1': 3, '2': 4 }
可以采用bind方法进行更改事件绑定的方法的参数及作用域。
function PhoneDrag(id) {var _this = this
this.oDiv = document.getElementById(id)
this.disX = 0
this.disY = 0
this.oDiv.addEventListener("touchstart", function (ev) {
_this.fnDown(ev)
}, false)
}
PhoneDrag.prototype.fnDown = function (ev) {
var _this = this
var oEvent = ev.touches[0]
ev.preventDefault()
this.disX = oEvent.clientX - this.oDiv.offsetLeft
this.disY = oEvent.clientY - this.oDiv.offsetTop
// 解除事件绑定的时候需要用到
var touchmoveHandle = function (ev) {
_this.fnMove(ev)
}
document.addEventListener("touchmove", touchmoveHandle, false)
document.addEventListener("touchend", function (ev) {
//这里是手指抬起的时候 如何删除touchmove事件
document.removeEventListerner('touchmove', touchmoveHandle, false)
}, false)
}
PhoneDrag.prototype.fnMove = function (ev) {
var oEvent = ev.touches[0]
var iX = oEvent.clientX - this.disX
var iY = oEvent.clientY - this.disY
this.oDiv.style.top = iY + "px"
this.oDiv.style.left = iX + "px"
}
window.onload = function () {
new PhoneDrag("div1")
}
for(i=0i<lis.lengthi++){lis[i].onmouseover=fun(i)
}
function fun(i){
this.style.backgroundPosition="left "+(-2-i*36)+"px"
}