其实只有两种使用方式,只不过每一种又细分是否传参。
先给一段html,后面会用来测试:
<p><button id=”test”>test</button></p>
<p id=”log”></p>
1,jquery.proxy(function, context);
使用context作为function运行上下文(即this)
2,jquery.proxy(function, context [, additionalarguments]);
传递参数给function
使用场景:click时,执行function,在给定的context里,同时传递两个参数,如果需要event,则可以作为function第三个参数。
注意:function执行的环境如果不适用proxy,则context会是当前点击对象,现在指定了其他的上下文,已经跟当前点击对象没有一点关系了。
var me = {
   /* i'm a dog */
   type: dog,
   
   /* note that event comes *after* one and two */
   test: function(one, two, event) {
     $(#log)
       /* `one` 是第一个附加参数,与对象`you`对应 */
       .append( <h3>hello  + one.type + :</h3> )
       /* `two` 是第二个附加参数,与对象`they`对应 */
       .append( and they are  + two.type + .<br> )
       /* `this` 是上下文,与普通对象`me`对应 */
       .append( i am a  + this.type + ,  )
  
       
       /* 事件类型是点击click */
       .append( thanks for  + event.type + ing  )
       /* `event.target`是被点击元素,类型是按钮button */
       .append( the  + event.target.type + . );
   }
 };
  
 var you  = { type: cat };
 var they = { type: fish };
  
 
 /* 一共4个参数:第一个是function,第二个是context,第三、四是参数 */
 var proxy = $.proxy( me.test, me, you, they );
 
 $(#test).on( click, proxy );
 /* 运行结果:
 hello cat:
 and they are fish.
 i am a dog, thanks for clicking the submit.
 */
在这种情况下,click仅仅相当于一个触发按钮,触发后执行的函数,跟click一点关系都没有了。
3,jquery.proxy(context, name);
使用场景:context是一个plainobject,name是其方法。在click时执行,但test函数执行的上下文是obj,不是$(“#test”)
var obj = {
     name: john,
     test: function() {
         console.log(this);
         $(#log).append( this.name );
         $(#test).off(click, obj.test);
     }
 };
 $(#test).on( click, jquery.proxy( obj, test ) );//在click时执行,但又
不是click的上下文
结果分析:在绑定点击事件后,第一次执行时,就把该绑定去除了。
去除之后,button上已经没有点击事件,所以再点击按钮,也不会有任何反应了。
4,jquery.proxy(context, name [, additionalarguments]);
一个疑问:
请教大家一个问题,
jquery.proxy(context, function, params);
与
function.call(context,params);
以上就是jquery.proxy的四种使用场景的实例详解的详细内容。
   
 
   