深入理解jQuery的proxy()

一、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值。


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值