这段js代码得拯救你多少时间

1.应用案例:
 
        var Mouse = function () {
// Look! no that = this!
this.position = [0, 0];
if (document.addEventListener) {
document.addEventListener('mousemove', ?); //this.move?
} else if (document.attachEvent) {
document.attachEvent("onmousemove", ?); //this.move?怎么放进去
}

};
Mouse.prototype.move = function (arg1,arg2,event) {
event = window.event || event;
var x = event.pageX || event.offsetX,
y = event.pageY || event.offsetY;
this.position = position = [x, y];
this.log(arg1,arg2);
};
Mouse.prototype.log = function (arg1, arg2) {
console.log(arg1+","+arg2);
console.log(this.position);
};
new Mouse();

上面你知道'?'号那里要干嘛了吗?我想给document的mousemove绑定我的move方法,但是遇到难题了,这样的话,Mouse.prototype.move

里的this就不会指向Mouse的对象,相信大家经常碰到这种问题.也许你早知道了怎么解决,但是有更快更简单的方法吗?答案是:

  Function.prototype.bind()这个神奇的玩意,但是ie6 7 8都不支持,一般现代浏览器都支持了,我们接下来要做的就是模仿他,

 这么好的方法当然要模仿它,怎么模仿见下面nothing的原创方法

    (function () {
var proxy = function (fn, target) {
var proxy = function () {
if (2 < arguments.length) {
var privateArgs = Array.prototype.slice.call(arguments, 2);
return function () {
var args = Array.prototype.slice.call(arguments);
Array.prototype.unshift.apply(args, privateArgs);
return fn.apply(target, args);
}
}
return function () {
return fn.apply(target, arguments);
}
}
return proxy.apply(null, arguments);
};
/*支持原生的使用原生的*/
Function.prototype.bind = Function.prototype.bind ||
function (target) { //这里的this指代要被代理的函数
if (1 < arguments.length) {
var args = Array.prototype.slice.call(arguments, 1); //取出参数列表
args.unshift(this, target); //这个args最终变成了[this,绑定的对象,参数列表]
return proxy.apply(null, args);
}
return proxy(this, target);
};
})();

有了以上代码,我们就可以轻松的实现了"?"号这里要写什么代码了,^_^,简单吧

 if (document.addEventListener) {
document.addEventListener('mousemove', this.move.bind(this,1,2));
} else if (document.attachEvent) {
document.attachEvent("onmousemove", this.move.bind(this,1,2));
}

 是不是以后凡是碰到要添加事件,然后调用的方法的this又想指向其他对象,这样是不是很简单呢..

原文地址:https://www.cnblogs.com/wichell/p/2289094.html