当前位置: 代码迷 >> 综合 >> jquery ---$.proxy()改变this指向的源码
  详细解决方案

jquery ---$.proxy()改变this指向的源码

热度:99   发布时间:2023-12-19 01:40:40.0
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指向改为document2、$.proxy(obj,'show')  / $.proxy(obj.show,obj)  obj是一个对象,show为obj下的一个function,这种情况是将show方法的this指向改向obj3、$.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为字符串,则主要针对的是情况2tmp = 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 bindargs = 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 removedproxy.guid = fn.guid = fn.guid || jQuery.guid++;return proxy;}</script>

 

  相关解决方案