var obj = {
show : function(){
alert(this);
}
};
$(document).click( $.proxy(obj,'show') );//obj下面的show方法的this指向obj
$.proxy(obj,'show') -> $.proxy(obj.show,obj)
一般写法是:$.proxy(方法名,this的指向者);
$.proxy()的要用法:
1、$.proxy(show,document);将show方法的this指向改为document
2、$.proxy(obj,'show') / $.proxy(obj.show,obj) obj是一个对象,show为obj下的一个function,这种情况是将show方法的this指向改向obj
3、$.proxy(show,document,3)(4); $.proxy(show,document)(3,4); 传参的情况;
<!--$.proxy()的要用法:
1、$.proxy(show,document);将show方法的this指向改为document
2、$.proxy(obj,'show') / $.proxy(obj.show,obj) obj是一个对象,show为obj下的一个function,这种情况是将show方法的this指向改向obj
3、$.proxy(show,document,3)(4); $.proxy(show,document)(3,4); 传参的情况
-->
<script>
var core_slice = [].slice;
function proxy( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) { //context为字符串,则主要针对的是情况2
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 ); //拿到参数集合
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
// args.concat( core_slice.call( arguments ) )这种写法是针对,如果arguments不是数组的情况的,要将其转为数组
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
}
</script>