码迷,mamicode.com
首页 > 其他好文 > 详细

proxy改变this指向

时间:2016-09-24 23:32:07      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

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);
});

 

proxy改变this指向

标签:

原文地址:http://www.cnblogs.com/gongshunkai/p/5904352.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!