proxy改变this指向

时间:2024-01-07 09:29:14
var core_slice = Array.prototype.slice;

var proxy = function(context,fn) {
var args, proxy; if ( typeof fn !== 'function') {
return undefined;
} args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context, args.concat( core_slice.call( arguments ) ) );
}; return proxy;
}; //调用1:
var show = function(){
alert(this);
}
proxy(document,show)(); //document //调用2:
var show = function(n1,n2){
alert(n1*n2);
alert(this);
}
proxy(document,show,3,4)(); //12 document
proxy(document,show)(3,4); //12 document
proxy(document,show,3)(4); //12 document //调用3:
var obj = {
show:function(n1,n2){
alert(n1*n2)
alert('obj -> show');
}
};
document.onclick = proxy(obj,function(){
this.show(3,4);
});