深入理解jQuery的proxy()

本文深入探讨了jQuery.proxy函数的原理和用途,详细解释了如何通过它实现事件委托,让开发者能够灵活地在JavaScript中进行函数绑定和执行。通过实例演示,读者将学会如何利用jQuery.proxy改变事件处理器内的作用域,以及如何通过指定对象来改变函数执行时的上下文。文章旨在提升开发者对JavaScript中闭包和作用域的理解,提供实用的技巧和代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、jQuery中源码:

            
// Bind a function to a context, optionally partially applying any
            // arguments.
            proxy: function(fn, context) {
                if (typeof context === "string") {
                    var 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
                var args = slice.call(arguments, 2),
                proxy = function() {
                    return fn.apply(context, args.concat(slice.call(arguments)));
                };

                // Set the guid of unique handler to the same of original handler, so it can be removed
                proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;

                return proxy;
            },


 

JQuery.proxy(function,context):
使用context代替function中的context。
比如:
var you = {
  type: "person",
  test: function(event) {
  $("#log").append( this.type + " " );
  }
$("#test").click(you.test);调用这句只有相当于调用:
$("#test").click(function(event){
         $("#log").append( this.type + " " );
});
所以这里的this指的是$("#test").
如果这样调用:$("#test").click($.proxy(you.test,you));
此时的调用相当于:
$("#test").click(function(event){
         $("#log").append( you.type + " " );

});
虽然调用事件的对象是$("#test"),但是却可以使用$.proxy把事件执行内的对象改变为you。
JQuery.proxy(context,functionname):
第一个参数是你想proxy的对象,第二个参数为要改变的函数的名字。
var obj = {
    name: "John",
    test: function() {
      $("#log").append( this.name );
      $("#test").unbind("click", obj.test);
    }
  };
$("#test").click( jQuery.proxy( obj, "test" ) );   把obj作为context传入test中,而不是$("#test").
这个执行完之后,结果会是John,
如果使用下面这句
$("#test").click(obj.test);
结果会是$("#test").的name值。


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值