proxy改变this指向

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);
});
原文地址:https://www.cnblogs.com/gongshunkai/p/5904352.html